通过create action将值传递给model

时间:2015-10-26 05:54:27

标签: ruby-on-rails

当我使用create action时,我试图将额外的值传递给我的模型:

现在我有一个产品清单,其中有2个按钮(尺寸M和尺寸L)可以添加到购物车中:

index.html.erb

<% products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.size.medium %> | <%= button_to 'Medium, line_items_path(product_id: product.id) %></td>
<td><%= product.size.large %> | <%= button_to 'Large, line_items_path(product_id: product.id) %></td>
</tr>

line_items_controller.rb

class LineItemsController < ApplicationController

 def create
  @cart = current_cart
  product = Product.find(params[:product_id])
  size = product.details.first.size
  @line_item = @cart.add_item(product_id, size.medium)

  respond_to do |format|
    if @line_item.save
      format.html { redirect_to :back,
        notice: 'Product was successfully created.'}
    else
      format.html { render action: "new"}
    end
 end
end
end

cart.rb

def add_item(product_id, size)
    current_item = picks.find_by_product_id(product_id)
    if current_item
      current_item
    else
      current_item = items.build(product_id: product_id, size: size)
    end
    current_item
 end

从我的代码中,我创建的每个项目都具有size:size.medium的值。如何重写我的代码,以便大小的值取决于我单击的按钮。因此,如果我点击按钮&#34; Large&#34;,我的line_item将保存product_id和size.large的值?

2 个答案:

答案 0 :(得分:1)

您可以将 额外参数 传递给button_to,然后通过params在控制器中访问它,如下所示。

<% products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.size.medium %> | <%= button_to 'Medium', line_items_path(product_id: product.id, size: 'Medium') %></td>
<td><%= product.size.large %> | <%= button_to 'Large', line_items_path(product_id: product.id, size: 'Large') %></td>
</tr>

在控制器中访问它params[:size]

class LineItemsController < ApplicationController

  def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    size = params[:size]
    @line_item = @cart.add_item(product_id, size)

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to :back, notice: 'Product was successfully created.'}
      else
        format.html { render action: "new"}
      end
    end
  end
end

答案 1 :(得分:0)

要为Pavan的回答提供一些上下文,您必须区分通过路由表单传递参数({{ 1}}创建一个小形式):

button_to

-

建议的#config/routes.rb resources :line_items #-> url.com/line_items 代码button_to是通过路径传递@pavan

虽然这样做会很好,但正确的方法是add the params to the button_to form itself

size

这会在表单中创建隐藏字段,如下所示:

<%= button_to 'Medium', line_items_path, params: { product_id: product.id, size: 'Medium' } %>

您还希望尽可能使用循环(以防止代码重复):

<input type="hidden" name="product_id" value="x">
<input type="hidden" name="size" value="y">