ruby-on-rails - has_one 不更新属性 id?

标签 ruby-on-rails postgresql

所以我有一个数据库关系,其中用户有一个 PreferenceList。我在数据库表中设置了一个preference_list_id,并与PreferenceList建立了belongs_to :user关系,并与User建立了has_one:preference_list关系。

这是奇怪的部分。如果我这样做user.preference_list =preference_list,我可以访问user.preference_list,它会给我正确的preference_list实例。但是,如果我执行 user.preference_list_id (我已检查过的有效列),即使我将preference_list 添加到user.preference_list 后,它也不会给我任何结果。我需要为各种数据库操作更新 id。我究竟做错了什么?

最佳答案

外键出现在声明belongs_to关联的类的表上。所以如果你有

class PreferenceList < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :preference_list
end

preferences_lists应该有user_id列。 Rails 将正确处理该列。您也可以将 preference_list_id 列添加到 users 表中。但该列没有特殊含义,Rails 默认情况下不会对它执行任何操作。如果确实需要操作preference_list_id,请尝试更改belongs_to/has_one。或者使用user.preference_list.id

关于ruby-on-rails - has_one 不更新属性 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18062051/

相关文章:

ruby-on-rails - 从 Heroku 下载 PG 数据库文件

ruby-on-rails - 无法推送到 github,ssh : Could not resolve hostname

ruby-on-rails - spree 路线: Adding only the api routes

postgresql - 防止在 PostgreSQL 中提取专有名词?

postgresql - 空的、不可编辑的 pg_hba.conf 文件

linux - Postgres : invalid argument: "psql"

ruby-on-rails - 警告 : the running version of Bundler is older than the version that created the lockfile error

ruby-on-rails - 如何在 Rails 中获取 twitter/friendfeed 之类的主页网址?

mysql - 访问 MySQL 数据库时出现 RoR 段错误

.net - 在 .NET 中使用 SSH 隧道连接到 postgresql