我有2個表(TableA和TableB)。一個has_many Bs。has_many關聯不添加列到表
On Rails的控制檯,這段代碼的第二行不起作用:
@a = TableA.new
@a.TableBs
我得到這個錯誤:PG :: UndefinedColumn:ERROR:......不存在
感謝您的幫助
我有2個表(TableA和TableB)。一個has_many Bs。has_many關聯不添加列到表
On Rails的控制檯,這段代碼的第二行不起作用:
@a = TableA.new
@a.TableBs
我得到這個錯誤:PG :: UndefinedColumn:ERROR:......不存在
感謝您的幫助
這是因爲您沒有正確設置表格,而且您正在查詢某個班級。
設置你的協會是這樣的:
class TableA < ActiveRecord::Base
has_many :table_bs, inverse_of: :table_a, dependent: :destroy
end
class TableB < ActiveRecord::Base
belongs_to :table_a, inverse_of: :table_bs
end
你相應的遷移應該是這樣的:
rails g migration create_table_as name:string
rails g migration create_table_bs name:string table_a:references
rake db:migrate
你的TableB
表格現在將有一個table_a_id
上,這是該協會凝固的地方。
現在,你就可以在你的IRB實例運行是這樣的:
@a = TableA.new
@b = TableB.new
@b.table_a = @a
@b.save
@a.table_bs
=> #<ActiveRecord::Associations::CollectionProxy [#<TableB id: 1, name: "Foo"]>
更新
這裏有inverse_of
一個小巧的解釋和dependent: :destroy
inverse_of
,使相關在Rails中更高效的對象查找。沒有將這些添加到你的關聯中,事實證明,關聯的Rails對象不會指向相同的內存中的對象。這意味着,如果沒有inverse_of
,您總是要訪問數據庫,以便Rails抓取關聯。但是,如果包含它,如果對象已經在內存中,那麼Rails將只抓取該對象!它本質上是一個雙向綁定的內存。
dependent: :destroy
用於父對象以確保關聯對象在銷燬父對象時銷燬。
可以解釋** inverse_of:**和** dependent:**是什麼意思? –
我已經爲你更新了我的答案! –
請爲您的模型顯示'TableA'和'TableB'的代碼。另外請注意,如果table_a has_many:table_bs,則TableBs不是* TableA的屬性或方法。您需要閱讀有關[活動記錄關聯]的Rails文檔(http://guides.rubyonrails.org/association_basics.html)。試試'@ a.table_bs'。 – lurker
沒有rails關聯宏(has_one,has_many等)添加列到數據庫。您需要通過創建遷移並運行'rake db:migrate'來自行添加它們。 http://guides.rubyonrails.org/active_record_migrations.html – max