Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 369
Jmbnx Avatar asked Jan 22 '23 23:01

Jmbnx


1 Answers

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
like image 88
Damien MATHIEU Avatar answered Feb 12 '23 12:02

Damien MATHIEU