Ruby on rails 3 使用嵌套属性保存数据时出现问题

Ruby on rails 3 使用嵌套属性保存数据时出现问题,ruby-on-rails-3,nested-attributes,Ruby On Rails 3,Nested Attributes,我是 我正在RubyonRails 3.0.7上构建一个网站,我想保存一个存储对象及其语言。因此,我有以下模型: class Store < ActiveRecord::Base belongs_to :user has_many :languages, :through => :store_languages has_many :store_languages accepts_nested_attributes_for :store_languages #V

我是

我正在RubyonRails 3.0.7上构建一个网站,我想保存一个
存储
对象及其
语言
。因此,我有以下模型:

class Store < ActiveRecord::Base
  belongs_to :user
  has_many :languages, :through => :store_languages
  has_many :store_languages

  accepts_nested_attributes_for :store_languages

  #Validations
  validates :title, :presence => true, :length => 5..100
  validates :contact_email, :presence => true, :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
end

class Language < ActiveRecord::Base
  has_many :stores, :through => :store_languages
  has_many :store_languages
end

class StoreLanguage < ActiveRecord::Base
  belongs_to :store
  belongs_to :language

  validates :store_id, :presence => true
  validates :language_id, :presence => true
end
视图:/stores/new.html.erb:

<%= form_for(@store) do |f| %>
  <% if @store.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@store.errors.count, "error") %> prohibited this store from being saved:</h2>

      <ul>
      <% @store.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <label for="title">Title*</label><br />
    <%= f.text_field :title %>
  </p>

  <p>
    <label for="description">Description</label><br />
    <%= f.text_field :description %>
  </p>

  <p>
    <label for="contact_email">Contact E-mail*</label><br />
    <%= f.text_field :contact_email %>
  </p>

  <p>
    <label for="logo">Logo</label><br />
    <%= f.file_field :logo %>
  </p>

    <% f.fields_for :store_languages do |lf| %>

      <%= lf.collection_select :language_id, @languages, :id, :name, {}, {:multiple => true } %>
    <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
当我从列表中选择两种语言创建一个新的存储时,它将在
store\u languages
表中保存以下内容:

 id |   name
 3    English
 4    Español
id |商店id |语言id 4 4 1

而且语言_id=1不存在

如果我在
create
操作中调试应用程序,我会得到以下结果:

"store"=>{"title"=>"asdasdsdsadasdasdasd", "description"=>"", "contact_email"=>"asdasdsa@asdasdsad.com", "logo"=>"", "store_languages_attributes"=>{"0"=>{"language_id"=>["3", "4"]}}}
您可以在这里看到ID是正确的:3和4。所以,我不知道为什么它可以节省1

有什么想法吗?

试试看

  <%= lf.collection_select :language_ids, @languages, :id, :name, {}, {:multiple => true } %>
true}%>

(即在属性名称中使用
ids
而不是
id

我在尝试该操作时遇到以下错误:未定义的方法'language\u ids'#
  <%= lf.collection_select :language_ids, @languages, :id, :name, {}, {:multiple => true } %>