问题描述:

Here are my relevant models:

class ListItem < ActiveRecord::Base

belongs_to :inventory_item

belongs_to :shopping_list

belongs_to :item

end

class ShoppingList < ActiveRecord::Base

has_many :list_items

belongs_to :user, :foreign_key => :user_id

end

class InventoryItem < ActiveRecord::Base

belongs_to :item, :foreign_key => :item_id

belongs_to :vendor

has_many :list_items

end

I want to have a button to create ListItems that belong to a user specified list that they own. The new ListItem also needs to be passed the respective :item_id and :inventory_item_id. Here's the relevant part of my current view:

<tr>

<% item.inventory_items.each do |product| %>

<td><%= button_to "#{product.price}",

{:controller => :list_items,

:action => 'create',

:id => #what goes here??,

:method => :create %></td>

<% end %>

</tr>

And my ListItems controller create method:

def create

ListItem.create

flash[:success] = "List Item Added."

redirect_to search_results_path(params[:search])

end

Clearly my create method isn't all that useful right now because it just creates a ListItem with no attributes other than :id. What's the best way to pass the appropriate parameters to my controller? Any help is much appreciated! Thanks in advance.

网友答案:

After doing a bunch of snooping around SO etc. I think the best way to accomplish this is to use a form with hidden fields, as below:

<%= form_tag("/list_items", method: "post") do %>
<%= hidden_field_tag(:item_id, item.id) %>
<%= hidden_field_tag(:inventory_item_id, product.id) %> 
<%= hidden_field_tag(:shopping_list_id, ShoppingList.first.id) %>
<%= submit_tag("#{product.price}") %>

This is working well for me and is cleaner in this instance than using a button_to.

相关阅读:
Top