更新联接表HABTM [英] Update join table HABTM
本文介绍了更新联接表HABTM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型之间的关系:
I have a relationship between two models:
房屋和人
class House
has_and_belongs_to_many :persons
end
我有加入像这样的表:
house_id | person_id | used
1 1 false
我需要使用以下代码将其更新为 true:
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.
推荐答案
我建议您使用以下三个表之间的has_many和belongs_to关系:人,房屋和
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)
编辑
,如果要向连接表中添加属性并与连接表进行交互,则永远不要使用HABTM(在解释)
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)
这篇关于更新联接表HABTM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文