开发者

Having trouble with many to many association nested forms

I am getting this error ActiveRecord::unknown attribute: store from dealcontroller,I am pretty sure has something to do with this line @deal=@city.deals.build(params[:deal]) is this correct for nested form?This is what i have.

   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

deal model

    class Deal < ActiveRecord::Base
belongs_to :city
has_many :stores ,:through =>:store_deals
has_many :store_deals
accepts_nested_attributes_for :store_deals
    end

store model

    class Store < ActiveRecord::Base
has_many :deals ,:through =>:store_deals
has_many :store_deals
    end

store-deal model

    class StoreDeal < ActiveRecord::Base
belongs_to :store
belongs_to :deal

    end

city model

     class City < ActiveRecord::Base
 has_many :deals 
     end

view

 <%= 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%>


If i'm not wrong (nested forms always give me headaches) it should better look like that :

model

class Deal < ActiveRecord::Base
  belongs_to :city
  has_many :stores ,:through =>:store_deals
  has_many :store_deals
  accepts_nested_attributes_for :stores
end

controller

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

view

<%= 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 %>

detailed information available here. There is also a Railscasts example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜