[英]Calling a model method with params in Rails
I have the following problem, lets say I have a table Users and a second table UserStrings for localization. 我有以下问题,可以说我有一个表Users和第二个表UserStrings用于本地化。 UserStrings has the following columns {user_id, language_id, full_name}
UserStrings具有以下列{user_id,language_id,full_name}
I also have a current_language method in ApplicationController that returns the id of the current language. 我在ApplicationController中也有current_language方法,该方法返回当前语言的ID。
I have to use a collection_select and I need to display user names of current language in the list. 我必须使用collection_select,并且需要在列表中显示当前语言的用户名。
<%= fb.collection_select(:id, User.all,:id, :full_name, {}, {})%>
The thing is that there is no full_name column in User table. 事实是,用户表中没有full_name列。 I know its possible to make a model method and call it instead of name.
我知道可以创建模型方法并调用它而不是名称。
<%= fb.collection_select(:id, User.all,:id, :model_method, {}, {})%>
This model method I wanted to run this little line 我想运行这种模式的方法
self.user_strings.find_by(:language_id => current_language).full_name
Here is the problem, I know that it is not possible to use a controller method in Models so I cant get the current_language in my Model. 这是问题所在,我知道无法在Models中使用控制器方法,因此无法在Model中获得current_language。 Is it possible to call the :model_method with param (current_language).
是否可以用param(current_language)调用:model_method。 If not is there any other way to get this working?
如果没有,还有其他方法可以使它正常工作吗?
ps. ps。 And no its not possible to rewrite the current_language as a new model method in Model because is more complex than it seems.
而且不可能将current_language重写为Model中的新模型方法,因为它比看起来要复杂得多。
Thanks in advance! 提前致谢!
Try this 尝试这个
def method_missing(m, *args, &block)
match = m.to_s.match(/regex of languages here/)
if match
self.user_strings.find_by(:language_id => match).first_name + self.user_strings.find_by(:language_id => match).last_name
else
nil
end
end
You can not it directly you need to define dynamic method for that 您不能直接为它定义动态方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.