我有一个房东和一个landlord_company模型。一旦创建了新的landlord_company,我试图将landlord_id传递给landlord_company表。我在landlord_company表单中有一个f.hidden_field,但它不起作用。
楼主模式:
has_many :landlord_companies
landlord_company模型:
belongs_to :landlord
landlord_company控制器:
def new
@landlord_company = LandlordCompany.new
end
def create
@landlord_company = LandlordCompany.new(landlord_company_params)
@landlord = Landlord.find(params[:landlord_id])
respond_to do |format|
if @landlord_company.save
format.html { redirect_to @landlord_company, notice: 'Landlord company was successfully created.' }
format.json { render :show, status: :created, location: @landlord_company }
else
format.html { render :new }
format.json { render json: @landlord_company.errors, status: :unprocessable_entity }
end
end
end
landlord_company form:
<div class="feedback-container">
<%= form_for @landlord_company, url: {action: "create"}, html: {class: "new.html.erb"} do |f| %>
<% if @landlord_company.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@landlord_company.errors.count, "error") %> prohibited this landlord_company from being saved:</h2>
<ul>
<% @landlord_company.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :llc_name, class: "general-text-label" %><br>
<%= f.text_field :llc_name, class: "general-text-field" %>
</div>
<div class="field">
<%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
</div><br>
<div class="actions">
<%= f.submit "Submit", class: "btn btn-black btn-4x" %>
</div>
<% end %>
</div>
routes.rb中:
resources :landlords do
member do
resources :landlord_companies
end
end
答案 0 :(得分:1)
将您的创建操作更改为:
def create
@landlord_company = Landlord.landlord_companies.new(landlord_company_params)
然后确保将landlord_id添加到&#34; landlord_company_params&#34;中的白名单参数中。方法,它将自动处理您的关联。
答案 1 :(得分:0)
经过近一天的工作后,我发现了什么是错的。我把资源嵌套错了。我把他们当作......
resources :landlords do
member do
resources :landlord_companies
end
end
......而且搞砸了一切!菜鸟错误。