我从dealcontroller收到此错误ActiveRecord::unknown attribute: store
,我很确定与此行有关
@deal=@city.deals.build(params[:deal])
对于嵌套表单是否正确?这就是我所拥有的。
class dealController < ApplicationController
def create
@city = City.find(session[:city_id])
@deal=@city.deals.build(params[:deal])
if @deal.save
flash[:notice]="successfully created"
redirect_to @deal
else
render 'new'
end
end
end
交易模式
class Deal < ActiveRecord::Base
belongs_to :city
has_many :stores ,:through =>:store_deals
has_many :store_deals
accepts_nested_attributes_for :store_deals
end
商店模式
class Store < ActiveRecord::Base
has_many :deals ,:through =>:store_deals
has_many :store_deals
end
商店交易模式
class StoreDeal < ActiveRecord::Base
belongs_to :store
belongs_to :deal
end
城市模型
class City < ActiveRecord::Base
has_many :deals
end
视图
<%= form_for @deal ,:url=>{:action =>"create"} do |f|%>
<%= f.text_field :item_name %><br/>
<%=f.fields_for :store_deal do |s| %>
<%=s.text_field :store_name %>
<%end%>
<%= f.submit "post"%>
<%end%>
答案 0 :(得分:1)
如果我没有错(嵌套表格总让我头疼),最好是这样:
<强>模型强>
class Deal < ActiveRecord::Base
belongs_to :city
has_many :stores ,:through =>:store_deals
has_many :store_deals
accepts_nested_attributes_for :stores
end
<强>控制器强>
def new
@city = City.find(session[:city_id])
@deal = @city.deals.build
@deal.stores.build
end
def create
@city = City.find(session[:city_id])
@deal = @city.deals.build(params[:deal])
# etc.
end
查看强>
<%= form_for @deal ,:url=>{:action =>"create"} do |f|%>
<%= f.text_field :item_name %><br/>
<%= f.fields_for :stores do |s| %>
<%= s.text_field :name %>
<% end %>
<%= f.submit "post" %>
<% end %>
详细信息here。还有Railscasts example