当用户喜欢评论create_notification
被触发在commet_like.rb:如何将模型与模型中的模型相关联?
class CommentLike < ActiveRecord::Base
after_create :create_notification
has_many :notifications
belongs_to :user
belongs_to :comment
validates :user, uniqueness: { scope: :comment }
belongs_to :liker, class_name: 'User', foreign_key: :user_id
belongs_to :liked_comment, class_name: 'Comment', foreign_key: :comment_id
private
def create_notification
notifications.create(
comment_like: self,
comment: comment,
user: comment.user,
read: false
)
end
end
我试图让这样的事情在通知指数工作:
<% if notification.comment_like_id %>
<% if notification.goal_id %>
liked <%= link_to "your comment", notification_goal_path(notification, notification.goal_id) %>
<% elsif notification.habit_id %>
liked <%= link_to "your comment", notification_habit_path(notification, notification.habit_id) %>
<% elsif notification.quantified_id %>
liked <%= link_to "your comment", notification_quantified_path(notification, notification.quantified_id) %>
<% elsif notification.valuation_id %>
liked <%= link_to "your comment", notification_valuation_path(notification, notification.valuation_id) %>
<% end %>
<% end %>
但问题是这些条件中的每一条都不可用于评论,因此通知显示为空白。
正如你在这里虽然可以看到CommentLike与评论相关联,在本例中给出comment_id: 1
和comment_id: 1
有valuation_id: 1
。
[1] CommentLike.find(1)
id: 1,
user_id: 1,
comment_id: 1,
[2] Comment.find(1)
id: 1,
content: "test",
goal_id: nil,
habit_id: nil,
valuation_id: 1,
quantified_id: nil,
commentable_id: nil,
commentable_type: nil,
user_id: 1,
likes: 1>
我们如何利用这个协会根据意见与其他4款协会做出正确的条件现身comment_like_id
下?
notifications_controller
def index
@notifications = current_user.notifications
@notifications.each do |notification|
notification.update_attribute(:read, true)
end
end
comment.rb
class Comment < ActiveRecord::Base
after_create :create_notification
has_many :notifications
has_many :comment_likes
has_many :likers, through: :comment_likes, class_name: 'User', source: :liker
belongs_to :habit
belongs_to :quantified
belongs_to :valuation
belongs_to :goal
belongs_to :user
private
def create_notification
author =
if goal
goal.user
elsif habit
habit.user
elsif quantified
quantified.user
elsif valuation
valuation.user
end
notifications.create(
comment: self,
habit: habit,
quantified: quantified,
goal: goal,
valuation: valuation,
user: author,
read: false
)
end
end
请让我知道如果你需要进一步的解释或代码: - ]
怎么来评论通过相关联的所有其他车型代替commentable(它看起来像你有该领域,但不是协会) – DVG