我有两个模型之间的关系:
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
发布评论