所以我有一条路线,我已经创建了一个form_for
new_offer_lead GET /offers/:offer_id/leads/new(.:format) leads#new
引导#new动作有效。
但是,让我说通过/ offers / 1 / leads / new提交offer_id没有传递给我的Lead模型。
Lead.column_names
Lead.column_names
=> ["id", "name", "email", "zip", "sport", "created_at", "updated_at", "offer_id"]
当我创建新的潜在客户时,我可以清楚地看到Lead模型中的新值,但offer_id为零。
模型
class Lead < ActiveRecord::Base
has_many :coupons
belongs_to :offer
class Offer < ActiveRecord::Base
has_many :leads
表格
<%= bootstrap_form_for(@lead, layout: :horizontal) do |f| %>
<div class="col-xs-4">
<p>
<%= f.text_field :name, :id => "myclass" %>
</p>
<p>
<%= f.text_field :email %>
</p>
<p>
<%= f.text_field :sport %>
</p>
<p>
<%= f.text_field :zip %>
</p>
<p id= "get-coupon-btn">
<%= f.submit "Get Coupon!", :class => "btn btn-primary" %>
</p>
</div>
路线:
Rails.application.routes.draw做
resources :offers do
resources :leads
end
devise_for :users
resources :offers
resources :coupons
resources :leads
我的主角#create controller action
def create
@lead = Lead.new(lead_params)
@offer = Offer.find(params[:offer_id])
if @lead.save
Coupon.assign_coupon(@lead)
redirect_to(@lead) #print the notice
else
render "new"
end
end
忽略assign_coupon事情。关于如何在创建潜在客户时将offer_id传递到主导模型的任何想法?试图了解嵌套资源并接受资源,但似乎无法将其与我目前的情况类比。谢谢!
更新1:现在这是错误的:无法找到提供带有&#39; =&#39; =
@offer = Offer.find(params[:offer_id])
答案 0 :(得分:1)
@offer = Offer.find(params[:offer_id])
@lead = @offer.leads.build lead_params
if @lead.save
.....
在关系属性上调用“build”函数,它将返回该关系对象(未持久化)的实例,其中包含引用它的对象的id。在这种情况下,它返回一个“Lead”实例,其值为offer_id。
答案 1 :(得分:0)
我认为您还需要更改form_tag:
<%= bootstrap_form_for([@offer,@lead], layout: :horizontal) do |f| %>
这应该会在您的控制器中为您提供offer_id
。