ruby on rails - How to show all messages between current user and another user? -
i'm getting better @ using clauses in rails running problem. have follow model setup:
class message < activerecord::base belongs_to :user belongs_to :recipient, class_name: 'user' end class createmessages < activerecord::migration def change create_table :messages |t| t.integer :user_id t.integer :recipient_id t.timestamps null: false end end end
in controller i'm trying show list of messages user_id
either current_user
or @message.recipient
or recipient_id
current user
or @message.recipient
. means, want show messages between current user , user whether current user sent or received it.
def show @message = message.find(params[:id]) @messages = message.all.where('user_id in (?) , recipient_id in (?)', @message.recipient_id, @message.recipient_id) end
but above doesn't work or using or
in statement. can't think out in head how accomplish this?
your sql searches
@messages = message.all.where('user_id in (?) , recipient_id in (?)', @message.recipient_id, @message.recipient_id)
both user , recipient ids using recipient id. should be
@messages = message.all.where('user_id in (?) , recipient_id in (?)', @message.user_id, @message.recipient_id)
you can do:
current_user.messages.where(recipient_id: @recipient.id)
or
@recipient.messages.where(user_id: @user.id)
edit:
to both directions, can try this: (untested)
@messages = message.all.where('user_id in (?) , recipient_id in (?)', [@message.user_id, @message.recipient_id], [@message.user_id, @message.recipient_id])
in
accepts arrays, can pass in both ids user , both recipient.
Comments
Post a Comment