Forum: Ruby on Rails Associations In rails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
27c1d5470227584808ba5d88c022e894?d=identicon&s=25 Charanya Nagarajan (charanya)
on 2009-04-23 12:52
Hi,
I have these Models in my app
User
Request
Requesttargetuser

Now User has the associations
has_many :requests

And the Request has the association
belongs_to :user

ie.A user can post a request.

But the request should be answered by certain users ie.I have to add
certain other users to reply for the request.

For that only I have this model called Requesttargetuser
I know i can use
in User model
has_many :requesttargetuser
has_many :requests :through=> :requesttargetuser

But my question is that can i have both has_many :requests and has_many
:requests :through => :requesttargetuser in the User table.Or else wat
will be the correct way to address this situation.

Thanks in advance
Fdb488647484e40f785dde7134afc6d1?d=identicon&s=25 Heinz Strunk (cojones)
on 2009-04-23 14:14
I don't know if I got your question right but what if you just:

User model:
has_and_belongs_to_many :requests

Request model:
has_and_belongs_to_many :users

and create a habtm table like:
create_table :users_requests, :id => false do |t|
  t.integer :user_id
  t.integer :request_id
end

Now you can assign as many users for as many requests as you want and
vice versa.
27c1d5470227584808ba5d88c022e894?d=identicon&s=25 Charanya Nagarajan (charanya)
on 2009-04-23 19:53
Thanks Heinz for the reply

I fixed the problem by using

User Model:

has_many :requests
has_many :requesttargetusers
has_many :targetrequests,:through=>
:requesttargetusers,:source=>:request

Request Model

belongs_to :user
has_many :requesttargetusers
has_many :targetusers, :through=> :requesttargetusers, :source=>:user

Requesttargetuser model:

belongs_to :users
belongs_to :requests

And this worked for me...



Heinz Strunk wrote:
> I don't know if I got your question right but what if you just:
>
> User model:
> has_and_belongs_to_many :requests
>
> Request model:
> has_and_belongs_to_many :users
>
> and create a habtm table like:
> create_table :users_requests, :id => false do |t|
>   t.integer :user_id
>   t.integer :request_id
> end
>
> Now you can assign as many users for as many requests as you want and
> vice versa.
This topic is locked and can not be replied to.