开发者

Ruby/Rails: difference between "@item" and "item" in a view

开发者 https://www.devze.com 2023-01-11 23:58 出处:网络
I have a view which might be rendered from a controller or as a partial from another view. In all the code I\'ve read, the controllers assign an instance variable \"@item\" and then call the view. On

I have a view which might be rendered from a controller or as a partial from another view.

In all the code I've read, the controllers assign an instance variable "@item" and then call the view. On the other hand, when rendering it as a partial, i开发者_如何学Ct receives a parameter "item".

So, all of my views start up this way:

item ||= @item

Very un-DRY. Is there a better way I am missing?


@item is an instance variable - it's visible to the whole class instance. For the purposes of Rails' views, you can think of them as "global" variables. If you have, for example:

class Foo
  def initialize
    @bar = "Yay!"
  end

  def show_bar
    puts @bar
  end
end

Then calling Foo.new.show_bar would print Yay!, because the @bar variable is visible to the whole instance.

item on the other hand is a local variable. It's only visible in the scope it was defined in. Rails uses instance variable to share data between the controller method and the view.

Typically, partials receive local variables because they aren't assumed to be in a 1:1 relationship with a controller method like standard views are. That is to say, a well-designed partial doesn't assume the presence of any instance ("global") variables. It is assumed that a full view will be rendered by data set by the controller method; it is assumed that partials are rendered by data explicitly passed in to them.

Since you're using this view as both, I'd suggest that you refactor it into the "just the partial, ma'am" piece and a full view wrapper piece. So, your full view may be as simple as:

<%=render :partial => "item_partial", :locals => {:item => @item} %>

Then, your item_partial would always use item rather than @item.

This gives you the ability to package all your reusable content up easily, and then add extra "fluff" for the full view as desired.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号