我觉得这只是一个简单的错误,我无法找出,但我还没有在网上找到任何帮助解释我做错了什么.我在Ruby on rails应用程序中创建了三个表:

Facility
 facility_name - string
 address       - string
 city_id       - integer
 state_id      - integer
 
 and foreign keys: cities, states

City
  city_name    - integer
  state_id     - integer

State
  state_short  - string
  state_long   - string

我把这些模型定义为:

class Facility < ApplicationRecord
  has_one :city
  has_one :state
end


class City < ApplicationRecord
  belongs_to :state
  belongs_to :facility
end

class State < ApplicationRecord
  has_many :cities
  belongs_to :facility
end

我认为我可以通过Rails控制台上的以下代码来调出该设施中的城市和州:

x = Facility.first
x.city_name
x.state_long

但这两个代码都给出了错误.我是不是误解了,通过将city_idstate_id放在Facilities表中,以及上面的关系,我应该能够从各自的表中获得city_namestate_long

推荐答案

class Facility < ApplicationRecord
  has_one :city
  has_one :state
end

这意味着citiesstates个表有facility_id

但在您的模式中,faciltiescity_idstate_id

这意味着您需要以这种方式更改您的关联

class Facility < ApplicationRecord
  belongs_to :city
  belongs_to :state
end

class City < ApplicationRecord
  belongs_to :state
  has_one :facility
end

class State < ApplicationRecord
  has_many :cities
  has_one :facility
end

另一种 Select 是更改架构(如果保留关联)

facilities
-----------
facility_name
address

cities
-----------
city_name
state_id 
facility_id

states
-----------
state_short
state_long
facility_id

换句话说,你在belongs_tohas_one之间是need choose

区别在于您将外键放在哪里(它出现在声明belongs_to关联的类的表中),但您也应该考虑数据的实际意义.has_one关系表示有一样东西是你的--也就是说,有东西指向你

在任何情况下,如果工具的实例没有city_namestate_long个方法,则会出现错误,因为添加关联并不定义关联模型的方法

你可以这样称呼它

facility = Facility.first
facility.city.city_name
facility.state.state_long

但可以添加这样的方法

class Facility < ApplicationRecord
  belongs_to :city
  belongs_to :state

  def city_name
    city.city_name
  end

  def state_long
    state.state_long
  end
end

或使用delegate方法

class Facility < ApplicationRecord
  belongs_to :city
  belongs_to :state

  delegate :city_name, to: :city
  delegate :state_long, to: :state
end

在那之后你可以这样称呼它

facility = Facility.first
facility.city_name
facility.state_long

Ruby-on-rails相关问答推荐

Rails版本7.1.2:当验证失败且控制器发送422状态时,JS停止工作

Rails ActiveRecord::LogSubscriber 不输出详细查询日志(log)

我可以向 erb 变量插值添加一个类吗?

Rails - Comment.count没有改变1

Ruby on Rails 7 与 React 集成

Rails Migration将字符串转换为整数?

rails 3.2 迁移无法在更改方法中向 create_table 添加索引

如何在 Ruby on Rails 中创建一个锚点并重定向到这个特定的锚点

Ruby - ActiveRecord::ConnectionNotEstablished

simple_forms 自定义数据属性

没有要加载的文件 - readline

如何在我的 Gemfile 中找到未使用的Ruby

Rails:使用 link_to 创建不带 href 的链接

在 rails 3 中批量插入

Ruby:如何将一种方法接收到的所有参数和块传递给另一种方法?

find、where 和 find_by_id 有什么区别?

从模型中获取验证

如何检测rails是否在根url?

Rails:如何将日期时间字符串解析为特定时区

Ruby/Rails CSV 解析,UTF-8 中的无效字节序列