使用模型中的方法,从视图中调用它 [英] Using a method within model, calling it from view

查看:68
本文介绍了使用模型中的方法,从视图中调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属于用户的更新模型. 为了显示一个用户的所有好友的更新,我正在做类似的事情:

I have an Update model which belongs to users. To show all of one user's friends' Updates, I am doing something like:

Update.where("user_id" => [array_of_friend_ids])

我知道做事的正确"方法是创建一个创建上述数组的方法.我开始编写该方法,但只能奏效.目前,我的用户模型中包含以下内容:

I know the "right" way of doing things is to create a method to create the above array. I started writing the method but it's only half-working. Currently I have this in my user model:

  def self.findfriends(id)
    @friendarray = []
    @registered_friends = Friend.where("user_id" => id)
    @registered_friends.each do |x|
      @friendarray << x.friend_id
    end 
    return @friendarray
  end 

我正在使用以下命令执行视图中的整个操作:

I am doing the entire action in the view with:

<% @friendinsert = User.findfriends(current_user.id) %>
<% @friendarray  = [] %>
<% @friendarray << @friendinsert %>
<%= @friendarray.flatten! %>

然后我调用可以正常工作的Update.where("user_id" => @friendarray).但是很明显,我在这里做事很卑鄙.我对Rails何时可以从视图中的模型和方法看到"某些变量感到有些困惑.插入ID数组以查找其更新的最佳方法是什么,因为我不应该在视图本身中使用太多逻辑?

Then I'm calling Update.where("user_id" => @friendarray) which works. But obviously I'm doing things in a very hacky way here. I'm a bit confused as to when Rails can "see" certain variables from models and methods in the view. What's the best way to go about inserting an array of IDs to find their Updates, since I'm not supposed to use much logic in the view itself?

推荐答案

Mattharick关于使用关联是正确的.您应该对问题描述中提到的问题使用关联.如果我们在您的问题的标题处提到该问题;

Mattharick is right about using associations. You should use associations for the question you mentioned in description of your question. If we come to the question at the title of your question;

假设您有一个User模型.

这两种方法是不同的:

def self.testing
  puts "I'm testing"
end

另一个是:

def testing
  puts "I'm testing"
end

请注意self关键字. self关键字使方法成为Class方法.您可以从控制器或诸如User.testing之类的视图中调用它.

Pay attention to the self keyword. self keyword makes method a Class method. Which you can call it from your controllers or views like: User.testing.

但是未经测试的是实例方法.可以这样称呼:

But the one with out testing is a instance method. Which can be called like:

u = User.last
u.testing

第二种方法使您可以在模型中使用实例"的属性.

Second one gives you possibility to use attributes of the 'instance' inside your model.

例如,您可以通过这种方法显示实例的name,就像这样吗?

For example, you can show name of your instance in that method just like this?

def testing
  puts "Look, I'm showing this instance's name which is: #{name}"
end

这些是功能强大的东西.

These are powerful stuff.

练习他们.

这篇关于使用模型中的方法,从视图中调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆