Render a rails partial based on the id of an action

a 夏天 提交于 2019-12-13 06:16:41

问题


I'm building a small ecommerce site that sells a variety of mens and womens clothing. i would like to render a partial based on which taxonomy the user is in. For example, if the user is at mysite.com/t/women/pants I would like to render _women.html.erb, or, if the user is at mysite.com/t/men/shirts I would like to render _men.html.erb.

I have a Taxonomy model that has_many taxons, and the Taxon model has_many products.

In taxons_controller.rb I have:

def show
  @taxon = Taxon.find_by_permalink(params[:id])
  return unless @taxon
  @taxonomy = Spree::Taxonomy.all
  @taxon_title = Spree::Taxon.all 

  @searcher = Spree::Config.searcher_class.new(params.merge(:taxon => @taxon.id))
  @searcher.current_user = try_spree_current_user
  @searcher.current_currency = current_currency
  @products = @searcher.retrieve_products

  respond_with(@taxon)
end

And in taxons#show I have: (which I know is wrong)

    <% @taxon_title.each do |title| %>
  <% @taxonomy.each do |taxonomy| %>
  <% if title.name == taxonomy.name %>
    <%= render "spree/shared/#{title.name.downcase}" %>
  <% end %>
  <% end %>
  <% end %>

When I go to mysite.com/t/women/long-sleeve the rails debugger displays :

controller: spree/taxons
action: show
id: women/long-sleeve

How do I access the id of the action im inside, so that in the controller/view I can do something like:

'if id equals 'women' render "spree/shared/#{title.name.downcase}"'

where title is the name of the taxonomy?

I imagine I need to find(params[:something] in the show action of the controller, but I'm a little unclear about params.

* * * @beck03076 That's a great trick. Thank you very much. But it's still not working.

In my controller I put:

@taxon_id = Spree::Taxon.find(params[:id])

Then in the action I put:

render 'spree/shared/women' if @taxon_id == params[:id]

And when I load the page it says 'the page you were looking for doesn't exist'. My partial is in the correct directory. Is my syntax correct?

My params are:

{"controller"=>"spree/taxons", "action"=>"show", "id"=>"women/long-sleeve"}

Thanks again for your help!


回答1:


Whenever you are unclear about params, just put the lines below in the action and execute the action.

p "****************************"
p params
p "****************************"

Now, goto the terminal in which you started your server.

Locate those two "*******" and everything thats in between them are params.

params is basically a ruby hash.

example:

params look like this, {:controller => "hello",:action => "bye", :id => 7, :others => "OK"}

In your controller to access the id, use params[:id].(=7)

to access others, use params[:others].(="OK")



来源:https://stackoverflow.com/questions/15349350/render-a-rails-partial-based-on-the-id-of-an-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!