开发者

build relationship from list of ids

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

开发者_如何学Go

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


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜