简体   繁体   English

has_many和belongs_to之间的关联

[英]Association between has_many and belongs_to

In an example database, associations are as follows: an Owner has_many homes and Home belongs_to Owner. 在一个示例数据库中,关联如下:所有者has_many homes和Home属于owner_to Owner。 I know I can call owner.homes to get a list of all their homes but in my View I only seem to be able to call the home.owner_id to get anything from the owner object. 我知道我可以调用owner.homes以获得所有房屋的列表,但是在我的视图中,我似乎只能调用home.owner_id从所有者对象中获取任何东西。

Is there a way to get around this? 有办法解决这个问题吗?

Home model: 家用型号:

belongs_to :owner, 
 inverse_of: :homes

params look like 参数看起来像

def home_params
    params.require(:home).permit(:street_address, :city, :state, :postal_code, :description, :owner_id)
  end

The ability to do home.owner is a natural outcome of what you've described, just as is owner.homes . 拥有home.owner的能力是您所描述的自然结果,就像owner.homes This is all covered in http://guides.rubyonrails.org/association_basics.html 所有内容都在http://guides.rubyonrails.org/association_basics.html中

If you can do home.owner_id , but not home.owner , that means that your database is set up properly, but you're missing the belongs_to :owner call in your Home model. 如果您可以执行home.owner_id ,但不能执行home.owner ,则意味着您的数据库已正确设置,但是您在Home模型中丢失了belongs_to :owner调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM