更新联接表HABTM

编程入门 行业动态 更新时间:2024-10-23 09:24:07
本文介绍了更新联接表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

本文发布于:2023-10-24 19:44:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524829.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HABTM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!