Возникли проблемы со многими ко многим вложенным формам ассоциаций - PullRequest
0 голосов
/ 06 октября 2011

Я получаю эту ошибку ActiveRecord::unknown attribute: store от dealcontroller, я почти уверен, что как-то связан с этой строкой @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 Ответ

1 голос
/ 06 октября 2011

Если я не ошибаюсь (вложенные формы всегда вызывают у меня головную боль), лучше выглядеть так:

модель

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

подробная информация доступна здесь . Также есть пример Railscasts

...