Forum: Ruby on Rails Deleting records in association

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.
Charanya N. (Guest)
on 2009-05-04 10:10
hi,
   i have 3 models
1.request
2.user
3.requesttargetuser

Requesttargetuser
belongs_to :request
belongs_to :user

User
has_many :requesttargetusers, :dependent=> :destroy
has_many :requests,:through => :requesttargetusers

Request
has_many :requesttargetusers,:dependent=> :destroy
has_many :users, :through=>:requesttargetusers

Now when i want to add a user as requesttargetuser for a request

I jus use

req=Request.find(:last)
targetuser=user.find(:last)

req.users<<targetuser

If i want to remove a user from the users list of a request,is there any
method similar to that of adding?

Thanks
Paco G. (Guest)
on 2009-05-04 15:47
You may try:

usertodelete = req.users.find(params[:id]) # Get the user to destroy
usertodelete.destroy



Charanya N. wrote:
> hi,
>    i have 3 models
> 1.request
> 2.user
> 3.requesttargetuser
>
> Requesttargetuser
> belongs_to :request
> belongs_to :user
>
> User
> has_many :requesttargetusers, :dependent=> :destroy
> has_many :requests,:through => :requesttargetusers
>
> Request
> has_many :requesttargetusers,:dependent=> :destroy
> has_many :users, :through=>:requesttargetusers
>
> Now when i want to add a user as requesttargetuser for a request
>
> I jus use
>
> req=Request.find(:last)
> targetuser=user.find(:last)
>
> req.users<<targetuser
>
> If i want to remove a user from the users list of a request,is there any
> method similar to that of adding?
>
> Thanks
Charanya N. (Guest)
on 2009-05-04 16:21
Paco G. wrote:
> You may try:
>
> usertodelete = req.users.find(params[:id]) # Get the user to destroy
> usertodelete.destroy
>

I do not want to delete the user .I want to delete the user entry in the
requesttargetuser table.

I Found out a way to do this

req=Request.find(:last)
user=User.find(:last)

req.users.delete(user)

Thanks Paco .
This topic is locked and can not be replied to.