Rails嵌套属性不保存

时间:2017-02-02 19:09:34

标签: ruby-on-rails ruby schema persistence

在我的模特中我有

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"}}

1 个答案:

答案 0 :(得分:1)

这是因为您的@blog尚未在数据库中保留,因此您不会拥有id

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

您应该能够Blog.create(blog_params)

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

相关问题