On Dec 13, 2010, at 2:40 PM, Marnen Laibow-Koser wrote:

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.

But I will remind you that the OP found that the problems came from Posts that did not have an associated User. In such cases, post.user will be nil and nil.empty? does not exist. Perhaps you meant to say unless post.user.blank?, but if there are many places where a post.user_name is used, the extra method avoids Law of Demeter violations. (Or "Suggestion of Demeter" if you prefer.)

-Rob



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
[email protected]

--
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- [email protected]. To unsubscribe from this group, send email to [email protected] . For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en .


Rob Biedenharn          
[email protected]     http://AgileConsultingLLC.com/
[email protected]               http://GaslightSoftware.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 [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to