简体   繁体   中英

Partials action inheretance rails

I asked a question here about creating an action for a partial. It was suggested that I either include a partial in a view (what partials are for), or make it its own view (no longer a partial). This has led me to ask a distinct question:

Do partials inherit actions from the views in which they are displayed?

Edit to answer first comment:

What I mean is if I have an index action and index view, and I display a partial in that view, will the partial understand the variables I define for the index action?

Okay,

based on the edit:

Theoreticaly, your partial knows about the instance variables defined in your controller. So you can simply call them in the partial. However it's more commong, and a good practise, to actually pass them along to the partial as variables: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials See option 3.4.4 : Passing local variables.

This makes your partial more usable. Otherwise you can only reuse the partial if you redeclare the variable in all controllers using this partial.

Yes, you partial that is a part of index template will know the same variables as index.

Keep in mind, it is not good practice to keep the partials dependent on instance variables since they can be reused anywhere! In order to remove the dependency send them in the partial as a local variable

So your index.html.slim (or html, or erb, whatever you use), can have:

render 'some_partial', items: @products

or somewhere else where you might call it:

render 'some_partial', items: @active_products

or as a full notation:

render partial: 'some_partial', locals: { items: @products }

hope you got the idea ;)

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