Rails最佳方式(或最佳实践)

时间:2017-01-30 14:26:23

标签: ruby-on-rails ruby ruby-on-rails-3

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

我一直在阅读以下帖子

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

众议院和所有者在数据库中与FK链接,因此1家公司拥有N个所有者,1家公司拥有N个房产。

模型用户链接到公司,因此1公司有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

1 个答案:

答案 0 :(得分:0)

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

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

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

同样适用于owner