很多关联嵌套表单都有问题

时间:2011-10-05 22:19:51

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 nested-forms nested-attributes

我从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%>

1 个答案:

答案 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