Simple Railsアプリ:ユーザーとイントロの2つのモデルがあります[これは単なるメッセージです]。各メッセージには、送信者(ユーザー)と受信者(ユーザー)があります。イントロモデルは次のとおりです(検証は省略)。
class Intro < ActiveRecord::Base
attr_accessible :content
belongs_to :sender, class_name: "User"
belongs_to :receiver, class_name: "User"
default_scope order: 'intros.created_at DESC'
end
そして今、ユーザーモデル:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :sent_intros, foreign_key: "sender_id", dependent: :destroy, class_name: "Intro"
has_many :received_intros, foreign_key: "receiver_id", dependent: :destroy, class_name: "Intro"
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
このアプリでは現在、現在のユーザーがイントロをフォームに送信し、そのメッセージに関連付けることができます(ホームページにはsent_introsが表示されます)。ただし、received_intros関数に関しては、intros_controller/createメソッドでいくつかのヘルプを使用できます。現在のユーザーによって作成されたイントロを別の特定のユーザーに関連付けて(つまり、送信して)、受信者の受信トレイにルーティングできるようにするにはどうすればよいですか?ありがとうございました。
class IntrosController < ApplicationController
before_filter :signed_in_user
def create
@sent_intro = current_user.sent_intros.build(params[:intro])
if @sent_intro.save
flash[:success] = "Intro sent!"
redirect_to root_path
else
render 'static_pages/home'
end
end
def index
end
def destroy
end
end