我有一个嵌套表单,我想在商店模型中包含city_id,这个<%= s.hidden_field :city_id, @city.id %>
是否正确?如果是,那之后我在控制器中添加了什么?如果它不是一个正确的方式来包括它,任何人都可以告诉我正确的方法吗?非常感谢。
<%= form_for @deal ,:url=>{:action =>"create"} do |c|%>
<%= c.text_field :item_name %>
<%= c.text_field :price %>
<%=c.fields_for :stores do |s| %>
<%=s.text_field :store_name %>
<%= s.hidden_field :city_id, @city.id %>
<%=s.text_field :address %>
<%end%>
<%= c.submit "post"%>
<%end%>
控制器
def create
@city = City.find(session[:city_id])
@deal=@city.deals.build(params[:deal])
if @deal.save
redirect_to @deal
flash[:notice]="successfully created"
else
render 'new'
end
end
模型
class City < ActiveRecord::Base
has_many :stores
has_many :deals
end
class Deal < ActiveRecord::Base
belongs_to :city
has_many :stores ,:through =>:store_deals
has_many :store_deals
end
class StoreDeal < ActiveRecord::Base
belongs_to :store
belongs_to :deal
end
错误
NoMethodError in Deal#new
Showing /home/Deals/app/views/deal/new.html.erb where line #13 raised:
undefined method `merge' for 2:Fixnum
Extracted source (around line #13):
10: <tr><td><label>Price</label></td><td><%= c.text_field :price %></td></tr>
11: <%=c.fields_for :stores do |s| %>
12: <tr><td><label>Store</label></td><td><%=s.text_field :store_name %></td></tr>
13: <%= s.hidden_field :city_id, @city.id %>
14: <tr><td><label>Cross street</label></td><td><%=s.text_field :address %></td></tr>
15: <%end%>
16: <tr><td><%= c.submit "post"%></td></tr>
答案 0 :(得分:3)
好的,现在我已经仔细查看了你的代码并且看到了问题是什么。 hidden_field
助手没有value
作为其参数之一。使用:
<%= s.hidden_field :city_id, :value => @city.id %>
然而,由于Michael Durrant指出的原因,最好在你的控制器中处理这个问题。