为什么一个模型不能从关联模型访问特定对象值?

时间:2016-01-03 14:05:42

标签: ruby-on-rails activerecord

背景: 我使用的是rails 4.0.4。我有两个模型:评论和这些评论的相关通知。 评论有一个发送通知的after_create过滤器:

def send_notification
  Notification.comment_created(self)
end

Notifications模型中的comment_created方法,目前正在生产中按预期工作:

def self.comment_created(comment)
  content = "[SENDER] replied \"#{n.truncate(comment.content, :length => 100, :omission => "...")}\" 
  create!(from_user: comment.user,
        to_user: comment.commentable.user,
        notifiable: comment.commentable,
        content: content,
        notification_type: 'REPLIED',
        comment_id: comment.id
        )
end       

现在,我已成功为评论添加了分页,因此每个评论都有一个属性:comment_page_num(字段类型为整数)。此列和新值在注释表以及rails控制台中正常显示。

def create
  @comment = @post.comments.new(comment_params.merge(user: current_user))
  if @comment.save
    last_page = [(@post.comments.without_parent.length.to_f / 10).ceil, 1].max
    @comment.update_attribute(:comment_page_num, last_page)           
  end
end

要使:comment_page_num属性可访问,我已在评论控制器中将其列入白名单:

def comment_params
  params.require(:comment).permit(:comment_page_num, :user_id, :post_id, :parent_id, :content)
end

现在我尝试将此值复制到创建的通知中:

def self.comment_created(comment)
  content = "[SENDER] replied \"#{n.truncate(comment.content, :length => 100, :omission => "...")}\" 
  create!(from_user: comment.user,
        to_user: comment.commentable.user,
        notifiable: comment.commentable,
        content: content,
        notification_type: 'REPLIED',
        comment_id: comment.id,
        page_num: comment.comment_page_num
        )
end     

但这会继续为page_num返回一个空值:

<ActiveRecord::Relation [#<Notification id: 923517, from_user_id: 2921, to_user_id: 2, notifiable_id: 47812, notifiable_type: "Post", notification_type: "REPLIED", content: "[SENDER] replied \"6:41\" to your post [SUBJECT]", is_read: nil, created_at: "2016-01-03 13:41:07", updated_at: "2016-01-03 13:41:07", comment_id: 76705, page_num: nil>]

当我将comment.comment_page_num替换为任何其他整数注释属性(如comment.user-id或comment.notifiable_id)时,它可以正常工作。似乎只有comment_page_num属性在此模型中不可访问。我错过了什么?

1 个答案:

答案 0 :(得分:0)

刚发现错误。这是因为我申请了

update_attribute(:comment_page_num, last_page) 

之后

if @comment.save

更改为此,现在可以使用:

def create
  @comment = @post.comments.new(comment_params.merge(user: current_user))
  last_page = [(@post.comments.without_parent.length.to_f / 10).ceil, 1].max
  @comment.update_attribute(:comment_page_num, last_page)       
  if @comment.save
    ....
  end  
end   

仍然不确定为什么它不可访问,如果值在DB中的注释模型和注释表中正确显示(在控制台中,这显示了正确的值:

Comment.find_by_id(4292).comment_page_num