【问题标题】:Rails 4 - has_one - Can't access attributes of related modelRails 4 - has_one - 无法访问相关模型的属性
【发布时间】:2013-12-25 15:55:02
【问题描述】:

我正在尝试开发一个小型 Rails 4 应用程序,但遇到了一些麻烦 - 与旧版 Rails 有很多不同。

当我尝试获取相关模型的属性时,收到PG::UndefinedColumn: 错误。相关模型通过has_one 关系关联,但我将在下面更好地解释我的模型。


现在我有以下架构:

网站(官方称为“项目”):

  • 身份证
  • 姓名
  • 说明
  • 网址
  • country_id(国家 FK)
  • category_id(FK 类别)

类别:

  • 身份证
  • 姓名

国家:

  • 身份证
  • 姓名

网站模型:

has_one :country
accepts_nested_attributes_for :country

has_one :category 
accepts_nested_attributes_for :category

国家和类别模型(两者相等):

has_many :site

迁移:

    # timestamp_add_column_idcountry_to_site
    # Adding reference (Foreign Key) of country to Site (Now Site will have a country_id field).
    add_reference :sites, :country, index: true

    # timestamp_add_column_idcategory_to_site
    # Adding reference (Foreign Key) of category to Site (Now Site will have a category_id field).
    add_reference :sites, :category, index: true

我的看法:

<%= @category.site.each do |store| %>
    <h1>Name: <%= store.name %></h1>
    <h3>Country: <%= store.country.name %> </h3>
<% end %>

错误:

(在商店中。国家/地区名称

PG::UndefinedColumn: ERROR:  column countries.site_id does not exist
LINE 1: SELECT  "countries".* FROM "countries"  WHERE "countries"."i...
                                                      ^
: SELECT  "countries".* FROM "countries"  WHERE "countries"."site_id" = $1  ORDER BY "countries"."id" ASC LIMIT 1

您还需要其他信息吗?如果是,请告诉我,我会尝试更快地编辑问题。 如何访问“site.country.name”属性?

P.S:我已经看到thisthis 的问题了。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 postgresql activerecord ruby-on-rails-4


    【解决方案1】:

    您的Site#has_one :country 必须是Site#belongs_to :country

    【讨论】:

      【解决方案2】:

      正如 janfoeh 所指出的,您的站点模型中应该有以下代码:

      belongs_to :country
      belongs_to :category
      

      这样,您可以使用Site.find(1).country 返回网站所在的国家/地区,或使用Country.find(1).sites 返回在某个国家/地区找到的所有网站。

      如果你想做“has_one”路由,你的数据模型应该是这样的:

      网站:

      • 身份证
      • 姓名
      • 说明
      • 网址

      类别:

      • 身份证
      • 姓名
      • site_id

      国家:

      • 身份证
      • 姓名
      • site_id

      您还应该将 Country 和 Category 模型的代码更改为:

      belongs_to :site
      

      【讨论】:

      • 这工作@Gjaldon,谢谢!还有一件事,对我来说,站点“属于”国家毫无意义。站点“有一个”国家,不属于。如果没有语义,还有其他方法可以做到这一点吗?
      • 我认为站点属于某个国家/地区也是有道理的,因此您可以使用Country.find(name: "UK").sites 列出在某个国家/地区找到的所有站点。如果您更喜欢使用 has_one 关联,我使用该方法更新了我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      相关资源
      最近更新 更多