简单的 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