views:

43

answers:

2

Hi I have has_and_belongs_to_many relationship between Posts and Comments and in my edit action I have form that returns me list of ids 1,3,5,8 etc. I want build relationship between my current model and all models which ids are in the list so @post.comments will return Comments with 1,3,5,8 ids

In fact I need execute

DELETE FROM comments_posts
WHERE post_id = @post.id

INSERT INTO comments_posts VALUES 
(1,@post.id)
(3,@post.id)
(5,@post.id)
(8,@post.id)

or do something similar

A: 

Maybe you are looking something like this.

list = params[:list].join(',') # Assumes space separated to begin with
@posts.comments.find(:conditions => ["id IN (?)", list])

UPDATE

Aside: I am surprised by the HABTM relationship in your application. Do you really mean that a post can have many comments and a comment can belong to many posts? Surely a comment belongs to only one post, no?

Nevertheless, I believe you can achieve what you're looking for as follows (using your examples):

@post.comments.destroy_all

@post.comments.create(...)

It's just basic associations in ActiveRecord

bjg
+1  A: 
params[:list] ||= []                # Create an empty array if form is empty
@posts.comment_ids = params[:list]  # Recreate comment associations

See also the Railscast about HABTM Checkboxes.

giraff
Of course! I wrote "comments_ids" instead of "comment_ids" and it's not the first time I do it :)
Bohdan Pohorilets