Rails 3 - 如何在更新操作中调用save之前将值赋给嵌套属性

时间:2013-03-14 12:50:11

标签: ruby-on-rails-3 validation attributes

模型关联是

document.rb

has_many :sections
accepts_nested_attributes_for :sections, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }

section.rb

belongs_to :document
has_many :paragraphs, :dependent => :destroy
has_many :contents :through => :paragraphs
validates :user_id, :presence =>  { :message => "Must be filled" }

paragraph.rb

attr_accessible :user_id, :section_id, :content_id
belongs_to :section
belongs_to :content
validates :user_id, :section, :content, :presence =>  { :message => "Must be filled" }

段落表就像一个段和内容的中间表,我想使用单个提交保存在文档,部分和段落表中的记录。 所以我将表单设计为

_form.html.erb

<%= form_for @document, :validate => true do |f| %>
    <%= f.error_messages %>
    <%= f.text_field :name %>
    <% f.fields_for :sections do |builder| %> 
   <%= builder.text_field :name %>
   <%= builder.select :content_ids .... {:multiple => true} %>
    <% end %>
<% end %>

提交表单时的示例参数

{"document"=>{"name"=>"sdf", "sections_attributes"=>{"0"=>{"name"=>"sdf", "description"=>"sdf", "_destroy"=>"0", "content_ids" => ["1", "2"]}}, "commit"=>"Update Document", "id"=>"3"}

另外,我正在将current_user的id更新为paragraph表的user_id列。

更新

@document = Document.find(params[:id])
@document.attributes = params[:document]
@document.sections.each {|section| 
  section.user_id = current_user.id 
  section.paragraphs.each {|paragraph| paragraph.user_id = current_user.id}
}
if @document.save!
  # success
else
  render :action => 'edit'
end

我收到了“验证失败:用户必须填写”。

使用object.attributes =如上所述

分配属性时是否触发验证

如何在调用save方法

之前将值分配给段落对象中的user_id

1 个答案:

答案 0 :(得分:0)

可能有帮助。

<%= f.hidden_field :user_id, value: current_user.id %>
相关问题