2013-03-14 34 views
0

模型協會是的Rails 3 - 如何調用保存的更新動作

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分配屬性時=如上

如何將值賦給調用保存方法

+0

驗證在保存時觸發。 – TheIrishGuy 2013-03-14 13:41:10

+0

我希望在分配屬性時執行驗證。在這之後@ document.attributes = params [:document]在模型的驗證錯誤消息中發生頁面錯誤。 – 2013-03-14 14:37:47

+0

建議您在該點使用帶有斷點和/或「放置user_id」的調試。 http://guides.rubyonrails.org/debugging_rails_applications.html – 2013-03-15 13:57:07

回答

0

可能有助於前一段對象user_id說明驗證觸發。

<%= f.hidden_field :user_id, value: current_user.id %> 
+0

我也認爲這但可能會被黑客入侵。 – 2013-03-14 14:40:58

+0

我跟隨了關於HABTM的ryan bates教程,通過在params中傳遞content_ids來保存段落內容。參考:http://railscasts.com/episodes/17-habtm-checkboxes。如何在這裏包含隱藏的文件?或者還有其他選擇嗎? – 2013-03-14 14:59:27