DRYing my views, helper / method / something else?
Have开发者_开发技巧 written some RoR sites in the past, but never bothered too much at DRYing up my views as it's only ever been me looking at the code.
Just starting a new site, that is likely to be a collaboration, and need help
I call this line multiple times in my views, and from multiple places.
<%= Person.find_by_id(rider.person_id).name %>
I'd like to be able to just do
<%= get_name(rider.person_id) %>
So I'd assume I'd put this code somewhere
def get_name=(id)
Person.find_by_id(id).name
end
But where? I've tried in the model and as a helper, but always get nomethoderror.
You're wrong in naming this method. Why you put "=" sign in the method name?
You should call this code only in controller, and in the views, only render result. The best place for this method is a helper.
def get_person_name_by_id(id)
Person.find_by_id(id).name || nil
end
try application_controller.rb
How about a method on the Rider class that just returns the name?
def name
person = Person.find_by_id( @person_id )
if !person.nil?
return person.name
end
return nil
end
used as
<%= rider.name %>
or, you could use a static/class method on the Person class.
def Person.get_name( rider )
if !rider.nil?
person = find_by_id( rider.person_id )
if !person.nil?
return person.name
end
end
return nil
end
called as
<%= Person.get_name( rider ) %>
Note that I dropped the reference to the id in the view code.
Rails is all about convention over configuration. All of it's helper methods assume the most common options unless overridden. However ActiveRecord models don't have a useful default to_s.
Specifying the default action:
class Person < ActiveRecord::Base
def to_s
name
end
end
Now every time you try to evaluate a person instance in string context you'll get a name.
So
<%= Person.find_by_id(rider.person_id).name %>
Can now be replaced with
<%= rider.person %>
For anything else you can specify field and methods.
精彩评论