嵌套模型和表单在Rails中具有一个直通关系

时间:2012-03-28 22:48:14

标签: ruby-on-rails ruby-on-rails-3

我正在尝试设置一个包含一些歌曲信息的表单。现在是歌曲名称和歌曲艺术家。

到目前为止,这是我的一些代码。

歌曲模型*编辑

class Song < ActiveRecord::Base

  has_one :song_artist_map
  has_one :artist, :through => :song_artist_map
  accepts_nested_attributes_for :artist

end

艺术家模型

class Artist < ActiveRecord::Base
  has_many :song_artist_maps
  has_many :songs, :through => :song_artist_maps
end

SongArtistMap模型

class SongArtistMap < ActiveRecord::Base
  belongs_to :song
  belongs_to :artist
end

歌曲控制器

def new 
  @song = Song.new
  @song.artist.build
end

在我的表单中,我添加了此代码

<% f.fields_for :artist do |a| %>
    <li><%= a.label :name %></li>
    <li><%= a.text_field :name %></li>
<% end %>

现在我的表格中没有任何东西出现在艺术家身上。

所以我需要一种方法,可以在添加歌曲时从表单添加艺术家,然后进行映射,或者只是在艺术家已经存在于我的数据库中时进行映射。

我知道我在这里做错了什么,有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

在你的歌曲模型中,它应该是has_many:艺术家?

如果你这样做

"artist".pluralize
 => "artists" 

这就是Rails用于自动查找一些东西的东西,特别是对于has_many关系,所以它可能是你问题的根源。

修改

在这种情况下,问题出在您的控制器中。而不是@ song.artist.build,你应该有@ song.build_artist。

使用has_many关系,Rails使用一个允许你实例化新的对象的对象,使用has_one,它只返回它(可以是nil。)。