Update join table HABTM

你。 提交于 2019-12-11 15:02:00

问题


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.


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/47460064/update-join-table-habtm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!