Ruby on Rails Monday, December 13, 2010

Rob Biedenharn wrote in post #968091:
> On Dec 12, 2010, at 4:59 PM, Rodrigo Mendona wrote:
>
>> other way is
>>
>> <%=p.user.name unless p.user.empty?%>
>
> Or, you can push that into the model and avoid the extra logic in the
> view:
>
> class Post
> def user_name
> self.user ? self.user.name : "(none)"
> end
> end
>
> <% @posts.each do |post| %>
> <%= post.user_name %>
> <% end %>

Why would you do that, though? Sure, it keeps a little bit of method
chaining out of the view, but at the cost of a completely unnecessary
model method.

If a calculation were being performed to get this value, I'd agree with
defining a method. But I think accessor method chaining in the view is
generally acceptable, particularly when it simply involves traversing
already loaded associations.

>
> You could name the method something like "author_string" or "by_line",
> too. The idea is to keep the view very clean.

Method chaining is much cleaner than this IMHO.

> You might be able to
> simply `delegate :name, :to => :user` in your Post model, but that
> would have given you the same problem if the post.user_id referred to
> a non-existent User.

delegate seems smelly in this context.

>
> -Rob

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment