【问题标题】:Rails nested attribute not savingRails嵌套属性不保存
【发布时间】:2017-02-03 03:49:55
【问题描述】:

在我的模型中我有

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

【问题讨论】:

  • 尝试将f.fields_for :tags 更改为f.fields_for :tags_attributes? @Edmund Lee 是正确的,您应该在此处使用 create 而不是 new 将对象保存到数据库。
  • 不,那没用。我只有 blog.new 那里,因为我的代码中有 blog.save ,但我的问题中没有包含
  • @brandoncodes @Glyoko,这是因为他正在验证 Tag 中是否存在 :id

标签: ruby-on-rails ruby schema persistence


【解决方案1】:

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

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

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

Rails 应该为您处理其余的事情。

【讨论】:

  • @brandoncodes 对不起我的疏忽。看我的编辑。在您的 Tag 模型中,从验证中删除 :id。
  • np !是的,我正要发布那个。这就是我刚刚所做的,它奏效了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多