简体   繁体   中英

What is the correct way to define an application-wide partial and its variables in rails

I am building a rails app that has a number of models, one of which is Items.

Items contains a short list of products and supporting information.

I need to display this information on every page in the app.

In my views I've added

<%= render @items %>

and then added the partial 'items/_item.html.erb'

Now, to get this all to work, I also need to define the variable

@items = Item.all

My question is, what is the correct way to define this variable? I could add this line to every view for every controller, but that doesn't seem very DRY.

Should I be defining this in the application controller? If so, will this cause any issues if I also want to maintain access to the Items index page?

Sorry if this is a simple question. I'm trying to think through the best approach, and haven't found much written about this case. Grateful for fresh ideas and perspective!

Thank you!

Do definitely should not call database from the view.

You can create private method inside application controller, and use it as before_filter for all controllers where @items collection is required. Most probably, you should customize actions where @items should be populated, like:

before_filter :load_items, :only => [:show, :edit, update]

If you need to display something, you should consider doing it in the Application controller, instead of in all the different controllers, and the view parts you could do in the layouts (since that is common through out the app). You can have the partial in the same folder (ie layouts), and call it in the layouts view as

<%= render :partial => 'partial_name' %>

And since you've done this at the application level, I don't think you'll required to render this partial from anywhere else in your app.

I think the easiest thing to do is to build a new partial (let's say we call it "items_box"). In your items/_items_box.html.erb , you define @items as Item.all, and supply whatever rendering code you need. Then all you have to do is change <%= render @items %> to <%= render 'items/items_box' %> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM