我有嵌套模型如下
Project
模型has_many
关键字和关键字belongs_to
项目
class Project < ActiveRecord::Base
has_many :url_list
has_many :keyword
accepts_nested_attributes_for :keyword, :allow_destroy => true
end
class Keyword < ActiveRecord::Base
belongs_to :project
attr_accessible :kw, :project_id
end
查看:
<%=form_for @project, :multipart => true do |f|%>
<ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :name%></li>
<li><%= f.text_field :name, :class => "txt_box1"%></li></ul>
<ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :request_id %></li>
<li><%= f.text_field :request_id, :class => "txt_box1" %></li></ul>
<ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= f.label :file%></li>
<li><%= f.file_field :uploaded_file%></li></ul>
<%= f.fields_for :keywords do |k|%>
<ul><li style = "width:85px; text-align: right; margin-right:5px; margin-top:5px"><%= k.label "keyword1" %></li>
<li><%= k.text_field :kw, :class => "txt_box1" %></li></ul>
<%end%>
<ul><li style="width:85px; text-align: right; margin-right:5px; margin-top:5px"> </li>
<li style="opacity: 0.8;"><div class="space"><%= f.submit "Submit", :class=> "button"%></div></li></ul>
<%end%>
我无法保存keywords
虽然它可以保存project
但我可能出错了?
关键字架构
class CreateKeywords < ActiveRecord::Migration
def change
create_table :keywords do |t|
t.string :kw
t.integer :project_id
t.timestamps
end
end
end
答案 0 :(得分:2)
在您的项目模型中尝试此操作:
has_many :keywords
accepts_nested_attributes_for :keywords, :allow_destroy => true
关键字 - 因为您有 has_many 关联。
如果它不起作用,请在log / development.log中检查你的参数 - 你应该有这样的东西:“keywords_attributes”=&gt; {“title”=&gt;“”......“}
查看此页面:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html