How to call a method?
I have a method find_all_media in model abc.rb. Model xyz and abc has relationship,
abc :has_many xyzs and
xyz :belongs_to abc
# abc.rb
method is in abc model
def self.find_all_media(media_name)
if self.media_name == self.xyz.media_name
return media_name
end
end
### view file
<% @abc.xyzs.each do |xyz| %>
<tr>
<td><%=h xyz.media_name %>开发者_JAVA技巧</td>
<td><%=h xyz.type %></td>
<td>I want to call method find all_media here ?? </td>
</tr>
I tried but not working, any
Seems like your
def self.find_all_media(media_name)
if self.media_name == self.xyz.media_name
return media_name
end
end
Method is a class method (self). So, you are trying to access you class method from your class instance
@abc
You have two options
1 - Make the method an instance method (by removing the 'self')
2 - Call your method as Abc.find_all_media
And just as a best practice,
Do not call models directly from your views, Do it through the controller, or helper
and if your 'find_all_media' method is someting to do with database query consider
:scope (in rails 3.x) (named_scope in rails 2.x)
HTH
sameera
Use Abc.find_all_media
. If youi use self
in method name it means this method is going to be used with model itself, not with object. Hope it'll help
精彩评论