【发布时间】:2017-01-30 14:26:22
【问题描述】:
我有一个模型,我不知道如何关注以下问题:
我一直在阅读以下帖子
- before_create in rails model
- before_create in user model -- set integer based on email (RAILS)
- Access current_user in model
我有一个项目,我想管理一些属性(资产)。 我有财产、所有者、公司和用户。
房屋和业主在 DB 中通过 FK 链接,因此 1 家公司有 N 个业主,1 家公司有 N 个属性。
模型 User 与 Company 相关联,因此 1 Company 有 N 个用户。
如何访问模型用户中的company_id,以便在创建属性和所有者时将此 ID 存储在属性和所有者模型中?
我必须在控制器和模型中这样做吗?
所有者类
class Owner < ApplicationRecord
acts_as_paranoid
has_many :property_owners
has_many :properties, :through => :property_owners
belongs_to :company
belongs_to :country
accepts_nested_attributes_for :properties
属性类
class Property < ApplicationRecord
acts_as_paranoid
has_many :property_owners has_many :owners, :through =>
:property_owners
belongs_to :company belongs_to :country
这是公司
Class Company < ApplicationRecord
has_many :properties
has_many :owners
最后一个是用户
class User < ApplicationRecord
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
before_create :set_default_role, only: :create
belongs_to :country
belongs_to :company
belongs_to :user_role
accepts_nested_attributes_for :company
【问题讨论】:
-
如果公司有很多用户、房屋和业主,这三个都应该有一个company_id字段。那么问题出在哪里,我不明白
-
是的,他们都有 company_id,我想将 company_id 存储在用户中关联的 House 和 Owner 中。当用户创建新房子或新所有者时,我想添加这个 id (company_id)
-
我会说它非常不清楚你在问什么,而且你似乎通常很困惑,也没有清晰的域模型。您正在寻找的很可能是
has_one through:和has_many through:关联。如果您实际上可以包含您的模型和一些关于您要解决的实际问题域的信息(例如,它是一个房地产应用程序还是您要构建什么?)那么这个问题可能是可以回答的。现在它很可能会被掩埋或关闭。 -
我添加了课程
-
在模型中使用
before_create不是正确的方法。这是专门为控制器回调编写的方法。模型有自己的回调系统(参见activerecord callbacks)。至于在模型中访问current_user,最好的方式是作为参数传递给方法调用。
标签: ruby-on-rails ruby ruby-on-rails-3