简体   繁体   中英

How to create form that switches between instances of a model?

I have a model, Product, and on the show view for this model, I want to have a select box for the user to be able to view a different Product. So, if a user's looking at the "Product 1" page, they can select "Product 2" from the select box and view that product.

Here's the code I'm using to create this select box:

<%= form_tag({:controller => "products", :action => "show"}, :method => :get) do %>
<%= select_tag :product_id, options_from_collection_for_select(Product.all, :id, :title) %>
<%= submit_tag 'Go' %>

But this doesn't work. I can choose a different product, and click Go, but it just goes to the same product, not the one I selected in the box.

What am I doing wrong here?

Basically, I'm trying to use a select box instead of something like this:

<% Product.all.each do |p| %>
    <%= link_to p.title, p %>
<% end %>

Here's what I have for my show action in the controller:

@product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
    flash[:alert] = 'The product you were looking for could not be found'
    redirect_to products_path

If you can post your code on the ProductsController for Show, it would clarify things more.

The id you want to use for "showing" the right product is passed by params[:product_id]. So you should be using that in your ProductsController

well a simple way would be to check if the params[:product_id] was passed by your form, if it is then use that instead of params[:id] basically:

if params[:product_id]
   @product = Product.find(params[:product_id])
else
   @product = Product.find(params[:id])
end

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