Jmbnx
Jmbnx

Reputation: 43

How can we delete rows from a join table by using ActiveRecord?

create_table "tags_pages", :id => false do |t|

  t.integer "tag_id", "page_id"

end

add_index "tags_pages", "tag_id"
add_index "tags_pages", "page_id"

How activerecord works on this table ? I want to insert and delete new rows. Sorry if it is a noob question.

Upvotes: 4

Views: 2162

Answers (1)

Damien MATHIEU
Damien MATHIEU

Reputation: 32629

Let's suppose you have one page and one tag.

# This will add a "tags_pages" entry, linking one page to one tag
page.tags << tag

# This will delete the appropriate "tags_pages" entry
page.tags.delete(tag)

You can also delete all the tags linked to one page with the clear method.

page.tags.clear

Upvotes: 9

Related Questions