gui12344455
gui12344455

Reputation: 23

Update join table HABTM

I have a relationship between two models:

House and Person

class House
   has_and_belongs_to_many :persons
end

I have a join table like this:

house_id | person_id | used
1          1           false

I need to update used to "true" using this code:

h = house.persons.find(params[:person_id])
h.update_attribute(:used, true) # ERROR used column doesn't exists in persons table

How can I update the column used in join table ? Thanks.

Upvotes: 0

Views: 861

Answers (2)

Erwin Rodriguez
Erwin Rodriguez

Reputation: 21

I would recommend the same except instead of PersonHouse, create an actual model called Lease or Deed with the attribute used. This should make your code alot cleaner.

Upvotes: 0

a131
a131

Reputation: 564

I would recommend you use the has_many and belongs_to relationships between your three tables: persons, houses and the join_table explicitly in code layer.

class House
   has_many :persons, through: :person_houses
   has_many :person_houses
end

class Person
   has_many :houses, through: :person_houses
   has_many :person_houses
end

#join table
class PersonHouse
   belongs_to :person
   belongs_to :house
end

Then you can update the used attribute as given below:

person_house = house.person_houses.find_by(person_id: params[:person_id])
person_house.update(used: true)

Edit you should never use HABTM, if you want to add attributes to your join table and interact with your join table (credit to max in the comments for explaining this)

Upvotes: 1

Related Questions