2017-04-25 127 views
1

创建一个新的has_many我试图使用Rails button_to在我的连接表中创建一个新的实例。我有4个型号(制造商,批次,报价和批发商) - 制造商has_many批次,批次has_many优惠,并has_many批发商通过优惠。批发商has_many优惠和has_many批次通过优惠。通过使用button_to

我在给定的批次中设置了“新优惠”视图,作为所有批发商的清单,以便制造商可以点击单个批发商旁边的按钮,该按钮将创建一个新的“优惠”批次和具体的批发商。

<%= button_to '+', {:controller => "offers", :action => "create", :wholesaler_id => wholesaler.id}, :method=>:post %> 

我的报价控制器创建方法:

def create 
    @offer = Offer.new(offer_params) 

    respond_to do |format| 
    if @offer.save 
     format.html { redirect_to @offer, notice: 'Offer was successfully created.' } 
     format.json { render :show, status: :created, location: @offer } 
    else 
     format.html { render :new } 
     format.json { render json: @offer.errors, status: :unprocessable_entity } 
    end 
    end 
end 

我offer_params方法在要约控制器:

def offer_params 
    params.require(:offer).permit(:batch_id, :wholesaler_id, :amount, :accepted, :ignored) 
end 

我得到一个错误,当我尝试,然后单击添加按钮 -

ActionController::ParameterMissing in OffersController#create 
param is missing or the value is empty: offer 

指的是offer_params方法。

由于我没有创建要约,直到我点击按钮,我不知道如何/我可以参考它。

感谢您的任何帮助 - 很高兴发布任何其他可能有用的回答代码。

全 '新' 的观点:

<div id="wrapper"> 
    <div id="unselected"> 
    <h2> Wholesalers</h2> 
    <table> 
     <thead> 
     <tr> 
     <th> Wholesaler </th> 
     <th> Add</th> 
     </tr> 
     </thead> 
     <tbody> 
     <% @unselected_wholesalers.each do |wholesaler| %> 
      <tr> 
      <td><%=wholesaler.name %></td> 
      <td><%= button_to '+', 
           {:controller => "offers", :action => "create", 
           :wholesaler_id => wholesaler.id}, 
           :method=>:post %></td> 
      </tr> 
     <% end %> 
     </tbody> 
    </table> 
    </div> 
</div> 
<%= link_to 'Back', manufacturer_batches_path(@manufacturer) %> 
+0

你能不能请附上'offer'形式,你用按钮来发送? – idej

+0

我不确定您的报价表单是什么意思?我没有使用表单部分,我刚刚在新的优惠视图中获得了代码 - 我已将完整的代码放在了我的文章中 –

回答

0

因为require声明,offer_params期待命名offer包含密钥batch_idwholesaler_id等的对象,应该是这样的:

{ 
    offer: { 
     batch_id, 
     wholesaler_id, 
     amount, 
     etc. 
    } 
} 

但它看起来像你的button_to发送这个:

{ 
    batch_id, 
    wholesaler_id, 
    amount, 
    etc. 
} 

最简单的解决办法是删除require声明,给你一个offer_params这样的:

def offer_params 
    params.permit(:batch_id, :wholesaler_id, :amount, :accepted, :ignored) 
end 
+1

谢谢!这工作,所以没有要求,但改变按钮为: '<%= button_to'+',{:controller =>“offers”,:action =>“create”,:offer => { :batch_id => @ batch.id,:wholesaler_id => wholesaler.id}},:method =>:post%>' –