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 %>
例如參數submiting形式
{"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分配屬性時=如上
如何將值賦給調用保存方法
驗證在保存時觸發。 – TheIrishGuy 2013-03-14 13:41:10
我希望在分配屬性時執行驗證。在這之後@ document.attributes = params [:document]在模型的驗證錯誤消息中發生頁面錯誤。 – 2013-03-14 14:37:47
建議您在該點使用帶有斷點和/或「放置user_id」的調試。 http://guides.rubyonrails.org/debugging_rails_applications.html – 2013-03-15 13:57:07