在我的模特身上
class Blog < ActiveRecord::Base
has_many :tags, :dependent => :destroy
accepts_nested_attributes_for :tags, :allow_destroy => true
end
class Tag < ActiveRecord::Base
belongs_to :blog
validates :blog, :name, presence: true
end博客控制器
def new
@blog = Blog.new
@blog.tags.build
end_form.html.erb
<%= form_for @blog, html: { multipart: true } do |f| %>
<div class="form-group">
<%= f.text_field :title, placeholder: 'Title', class: ('form-control') %>
</div><br>
<%= f.fields_for :tags do |builder| %>
<div class="form-group">
<%= builder.text_field :name, placeholder: 'Tags' %>
</div><br>
<% end %>
<div class="actions text-center">
<%= f.submit 'Submit', class: 'btn btn-primary' %>
</div>
<% end %>博客控制器
def create
@blog = Blog.new(blog_params)
binding.pry
end
def blog_params
params.require(:blog).permit(:title, :author, :text, :avatar, :banner, :tags_attributes => [:id, :name])
end在我的绑定中,它说@blog的错误消息是它无法保存,因为标记对象缺少一个blog_id。我到处寻找,我试图复制我的代码,以匹配其他解决方案,但没有成功。
如果有帮助的话,在我提交表格的时候,我会收到这个
"tags_attributes"=>{"0"=>{"name"=>"dsfsf"}}发布于 2017-02-02 19:18:10
这是因为您的@blog还没有持久化在db中,所以您将没有id。
在Tag模型中,从验证中删除:id。
你应该可以只做Blog.create(blog_params)
Rails应该为您处理剩下的部分。
https://stackoverflow.com/questions/42010414
复制相似问题