2017-11-23 36 views
0

に参加:更新私は2つのモデル間の関係を持つテーブルHABTM

ハウスと人

class House 
    has_and_belongs_to_many :persons 
end 

私はこのようなテーブルに参加している:

house_id | person_id | used 
1   1   false 

私がするために使用更新する必要がありますこのコードを使用して「true」:

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

結合テーブルで使用される列を更新するにはどうすればよいですか?おかげさまで

+0

しかし、あなたはHABTMを使用する必要があります:http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has- - と多数に属します – Kris

+1

結合表に余分なデータを格納する場合は、HABTMを使用しないでください。 'has_many though:'を使ってください。 HABTMは非常に制限されており、間接的に結合テーブルを作成/照会することしかできません。 – max

答えて

1

3人のテーブルの間にhas_manyとbelongs_toの関係を使用することをお勧めします。人物、住宅、明示的にコードレイヤーのjoin_table。

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 

下記のようにあなたが使用する属性を更新することができます。

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

編集 あなたがあなたの結合テーブルに属性を追加したい場合は、HABTMを使用していないし、あなたの参加と対話んテーブル(これを説明するためのコメントの最大のクレジット)

+0

NoMethodError(未定義メソッド 'to_sym 'for nil:NilClass 意味ですか?): – gui12344455

+0

このエラーは、結合テーブルのインスタンスを更新するときに発生しますか?どのバージョンのレールを使用していますか? – xeon131

+0

はい、次の行にあります:person_house.update(使用:true) – gui12344455

関連する問題