Rails 嵌套属性未保存

Rails nested attribute not saving

在我的模型中我有

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 的错误消息是无法保存,因为 Tag 对象缺少 blog_id。我到处都看过,我试图复制我的代码以匹配其他解决方案,但没有成功。

如果有帮助,在我提交表单时在我的参数中得到这个

"tags_attributes"=>{"0"=>{"name"=>"dsfsf"}}

那是因为你的 @blog 还没有保存在数据库中,所以你不会有 id

在您的 Tag 模型中,从验证中删除 :id

你应该可以做到 Blog.create(blog_params)

Rails 应该会为您处理剩下的事情。