モデルの関連付けは
ドキュメント.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" }
段落.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 を段落テーブルの 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 に値を割り当てる方法