Simple rails app: I have 2 models, user and intro [which is simply a message]. Each message has a sender (user) and receiver (user). Here’s the intro model (validations omitted):
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
and now the user model:
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
The app currently lets the current user submit an intro into a form and associate with that message (a home page shows sent_intros). However, I could use some help in the intros_controller/create method when it comes to the received_intros function. How do I let an intro that is created by the current user be associated with (i.e. sent to) another specific user so that I can route it to a recipient’s inbox? Thank you.
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
It doesn’t look like you’re allowing the current_user to assign a
receiverto an intro they create? You need to have an input on your form that allows a user to set a validreceiver_id, and you need to add receiver_id to attr_accessible:With that, when your
introis created, it will be properly associated with both a sender and a receiver. You would then be able to access a current_user’s received intros with the methodcurrent_user.received_introsYou may want to add some validation to the
Intromodel to make sure both a receiver and a sender exist.EDIT: You can add the receiver_id field to your code in the comments like so: