开发者

How to use find_all_by on a hash

I have a simple messaging system in Rails with a Message table for the original information and a MessageCopy table for each recipient's information.

Message includes job_id, subject, body, and author_id.

MessageCopy includes recipient_id and message_id.

I am trying to isolate a specific set of messages. I need the recipient to see all message_copies that are 1. addressed to the recipient, and 2. belong to any message with message.job_id = @job.id. Something like?

@jobmessages = Message.find开发者_如何转开发_all_by_job_id(job.id)
@messages = MessageCopy.find_all_by_recipient_id_and_message_id(current_user.id, @jobmessages.id)

How can you do a find_all_by when one of the criteria is a hash like @jobmessages?

Thanks!


Assuming you have the following associations:

class User 
 has_many :jobs
end

class Job
 belongs_to :user
 has_many :messages
 has_many :message_copies, :through => :messages
end

class Message
 belongs_to :user
 belongs_to :job
 has_many :message_copies
end

class MessageCopy
 belongs_to :message
 belongs_to :recipient, :class_name => "User"
end

You can get the MessageCopy given a Job and the current user as follows:

job.message_copies.find_all_by_recipient_id(current_user.id)


I believe you can use the following

@jobmessages = Message.find_all_by_job_id(job.id) 

@messages = MessageCopy.all(:conditions => 
   ["recipient_id = ? AND message_id IN (?)",
   current_user.id, @jobmessages.map(&:id)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜