3

假設我有兩個模型;張貼&評論接受嵌套屬性和過濾器

class Post < ActiveRecord::Base 
    has_many :comments 
    accepts_nested_attributes_for :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 

    before_save :do_something 

    def do_something 
    # Please, let me do something! 
    end 
end 

我有發表形式,徵求意見領域。一切都按預期工作,除了過濾器。通過上述配置,不會觸發Comment_size前的before_save過濾器。

你能解釋一下爲什麼,我該如何解決這個問題?

回答

1

在這種情況下,Rails不會單獨實例化和保存註釋。你會好起來的帖子你的模型中加入一個回調來處理這種嵌套評論:

class Post < AR::Base 
    before_save :do_something_on_comments 
    def do_something_on_comments 
    comments.map &:do_something 
    end 
end 
+0

謝謝你的回答。但是,讓我們說,我想避免這種技術。有沒有其他方法可以達到完全相同的結果?也許在關聯上有一些參數?類似於「has_many:comments,:autosave => true」或「accep_nested_attributes_for:comments,:touch => true」? – christianblais

0

據布賴恩Helmkamp,最好使用窗體對象模式比它是使用accepts_nested_attributes_for。看看7 Patterns to Refactor Fat ActiveRecord Models

也許你可以做這樣的事情?

class NewPost 
    include Virtus 

    extend ActiveModel::Naming 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 

    attr_reader :post 
    attr_reader :comment 

    # Forms are never themselves persisted 
    def persisted? 
    false 
    end 

    def save 
    if valid? 
     persist! 
     true 
    else 
     false 
    end 
    end 

private 

    def persist! 
    @post = Post.create! 
    @comment = @post.comment.create! 
    end 
end 

do_something在創建註釋時會被調用。