On 13 December 2010 19:40, Marnen Laibow-Koser <[email protected]> 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.

The method DRYs up the code by not having to repeat
self.user ? self.user.name : "none"
wherever user name is to be displayed.  Also it means the text to be
used when there is no user is defined in the model rather than being
scattered around the views.

Colin


Colin

>
> 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
> [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 [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.
>
>

-- 
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