【问题标题】:Rails best way (or best practices)Rails 最佳方式(或最佳实践)
【发布时间】:2017-01-30 14:26:22
【问题描述】:

我有一个模型,我不知道如何关注以下问题:

我一直在阅读以下帖子

我有一个项目,我想管理一些属性(资产)。 我有财产、所有者、公司和用户。

房屋和业主在 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


【解决方案1】:

考虑到您的关联正确,在您的控制器中,当用户创建例如房屋条目时:

def create
     @property = current_user.company.properties.new(property_params)
     ....
 end

其中current_user 可以替换为包含当前登录用户的变量,property_params 是强参数,从您的表单发送到控制器。

owner 也是如此

【讨论】:

  • 我收到 nil:NilClass 的未定义方法 `properties',我假设 current_user 来自设计作为默认值,如果我在视图中看到原始 current_user.company_id,我会看到存储的值在用户模型中
  • 用户有公司吗?
  • 什么意思?
  • 此消息表示当前用户没有公司(公司为 nil)。根据您的模型,应该有“@user.company”或“current_user.company”,因为用户“属于:company”...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
  • 2010-09-22
相关资源
最近更新 更多