假设我们有抒情模式:的Rails在一个视图中的两个连接的模型
class Lyric < ActiveRecord::Base
belongs_to :song
end
与宋型号:
class Song < ActiveRecord::Base
has_many :artist, :through => :artistsong
belongs_to :album
has_one :lyric
accepts_nested_attributes_for :lyric #is this needed?
end
迁移脚本歌曲:
class CreateSongs < ActiveRecord::Migration
def change
create_table :songs do |t|
t.integer :track
t.string :name
t.references :album
t.timestamps
end
add_index :songs, :album_id
end
end
的歌词迁移脚本:
class CreateLyrics < ActiveRecord::Migration
def change
create_table :lyrics do |t|
t.text :lyric
t.references :song
t.timestamps
end
add_index :lyrics, :song_id
end
end
假设我有一首名为“歌曲1”的歌曲,并在数据库中附有歌词。
所以歌曲表:
|id|name |
-------------------------
|1 |song1 |
和歌词表:
|id|song_id|lyrics |
---------------------------------
|1 |1 |blahblah |
在song_controller.rb的编辑方法:
# GET /songs/1/edit
def edit
@song = Song.find(params[:id], :include=>:lyric)
end
这是编辑的观点歌曲:(在Matteo建议的修复之后)
<%= form_for(@song) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% f.fields_for :song_text do |child_form| %>
<%= child_form.label :lyrics %><br />
<%= child_form.text_field :lyrics %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
如果我这样做:
<%= debug(@song.lyric) %>
我可以看到歌词的内容:
--- !ruby/object:Lyric
attributes:
id: 1
song_text: hid
song_id: 2
created_at: 2012-02-07 00:59:14.000000000Z
updated_at: 2012-02-07 07:21:57.000000000Z
但在歌词文本区域完全消失的观点...
我希望能够以相同的形式编辑歌曲的名称和歌词,这可能吗?
感谢
添加了歌词和歌曲的迁移脚本 – Bill 2012-02-07 07:40:17
你可以尝试更改表格歌词中包含歌词的字段的名称,并在fields_for中使用新名称。也许像song_text或lyric_text。 – 2012-02-07 07:45:02
对不起,我是第一次使用红宝石的用户,我想我改变了适当的地方。 – Bill 2012-02-07 07:54:37