まず、あなたはこのようなあなたのコントローラーを向上させることができます
def create
@message = current_user.messages.new(params[:message])
if @message.save
flash[:message] = "Private Message Sent"
end
redirect_to user_path(@message.to_id)
end
次に、あなたのモデルに:
# app/models/message.rb
class Message < ActiveRecord::Base
belongs_to :user
belongs_to :recipient, class_name: 'User', foreign_key: :to_id
has_many :notifications, as: :event
after_create :send_notification
private
def send_notification(message)
message.notifications.create(user: message.recipient)
end
end
# app/models/user.rb
class User < ActiveRecord::Base
has_many :messages
has_many :messages_received, class_name: 'Message', foreign_key: :to_id
has_many :notifications
end
# app/models/notification.rb
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :event, polymorphic: true
end
このNotification
モデルでは、さまざまな「イベント」のために、ユーザの通知を保存することができます。通知が読み取られたかどうかを保存したり、通知されたユーザーに電子メールを送信するためにafter_create
コールバックを設定することもできます。
このNotification
モデルの移行は、次のようになります。
# db/migrate/create_notifications.rb
class CreateNotifications < ActiveRecord::Migration
def self.up
create_table :notifications do |t|
t.integer :user_id
t.string :event_type
t.string :event_id
t.boolean :read, default: false
t.timestamps
end
end
def self.down
drop_table :notifications
end
end
あなたはRailsの関連付けオプションhereについて読むことができます。
おかげさまでお世話になりました!私はこの前の笑を得たいと思う。私は自分のメッセージモデルのread_at属性を作成して、ユーザーがメッセージを表示するアクションに入ると、タイムスタンプを作成します。私のアプリケーションのヘルパーには、そこに何個の無限オブジェクトがあるか(未読を意味する)を見るメソッドがあります。私はあなたのコードについてもっと深く考えます。その興味深い=)前に多態性について聞いたことがない – Sasha