我有發佈和評論模型。模型中的after_create動作未更新父模型的屬性?
我要實現以下目標:每個帖子創建或註釋的:content_changed_at
屬性後,應更新created_at
時間:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names, :content_changed_at
has_many :comments, :dependent => :destroy
def init_sort_column
self.content_changed_at = self.created_at || Time.now
end
end
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :post, :counter_cache => true
after_create :update_parent_sort_column
private
def update_parent_sort_column
if self.post
self.post.content_changed_at = self.created_at
end
end
end
content_changed_at
創建帖子的時候(與初始created_at
正在更新日期)。但由於某些原因,該屬性在郵件評論時未更新。
這是怎樣一個後評論創建:
comments_controller.rb:
def create
@post = Post.find(params[:post_id])
comment_attr = params[:comment].merge :user_id => current_user.id
@comment = @post.comments.create(comment_attr)
redirect_to post_path(@post)
end
在創建後生成的SQL:
#<Post id: 64, title: "tttttttttest", content: "hello", user_id: nil, created_at: "2012-03-12 10:07:29", updated_at: "2012-03-12 10:07:29", comments_count: 0, total_votes: 0, content_changed_at: "2012-03-12 10:07:29">
每一個被現在工作正常:content_changed_at: "2012-03-12 10:07:29
當您創建時生成的SQL一個職位評論:
(0.2ms) SAVEPOINT active_record_1
SQL (1.5ms) INSERT INTO "comments" ("content", "created_at", "post_id", "total_votes", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?) [["content", "teststsetsetset"], ["created_at", Mon, 12 Mar 2012 10:10:09 UTC +00:00], ["post_id", 64], ["total_votes", 0], ["updated_at", Mon, 12 Mar 2012 10:10:09 UTC +00:00], ["user_id", nil]]
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 64 LIMIT 1
SQL (0.4ms) UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1 WHERE "posts"."id" = 64
(0.2ms) RELEASE SAVEPOINT active_record_1
=> #<Comment id: 51, content: "teststsetsetset", post_id: 64, user_id: nil, created_at: "2012-03-12 10:10:09", updated_at: "2012-03-12 10:10:09", total_votes: 0>
現在如果我再次檢查後:
content_changed_at: "2012-03-12 10:07:29
的日期是相同的。
任何建議來解決這個問題?
你似乎是更新後的屬性但不保存帖子。如果您在回調中調用'self.post.save'作爲第二行,會發生什麼? – 2012-03-12 10:25:16