创建用户后保存Rails关联

时间:2016-03-18 00:15:19

标签: ruby-on-rails activerecord

我是Rails和ActiveRecord的新手,需要一些帮助。基本上,我有4个模型:UserPropertyPropertyAccountAccountInvitation。用户和属性通过PropertyAccounts建立了多对多的关系。 AccountInvitations有一封用户的电子邮件和property_id

我想要发生的是,在用户在我的应用程序上注册后,他的用户帐户会自动与某些预先创建的属性相关联。我不知道该怎么做是编写查询以从AccountInvitations获取Property对象并将它们保存到User对象。有关我的伪代码,请参阅 def assign_properties 。欢迎任何帮助,非常感谢!

class User < ActiveRecord::Base
  has_many :property_accounts
  has_many :properties, through: :property_accounts
  after_create :assign_properties

  # Check to see if user has any pre-assigned properties, and if so assign them
  def assign_properties
    account_invitations = AccountInvitations.where(email: self.email)

    if account_invitations.any?
      account_invitations.each do |i|
        properties += Property.find(i.property_id)
      end
      self.properties = properties
      self.save
    end
  end
end

class AccountInvitation < ActiveRecord::Base
    belongs_to :property
    validates  :property_id, presence: true
    validates  :email, uniqueness: {scope: :property_id}
end

class Property < ActiveRecord::Base
  has_many :account_invitations
  has_many :property_accounts
  has_many :users, through: :property_accounts
end

class PropertyAccount < ActiveRecord::Base
  belongs_to :property
  belongs_to :user
end

2 个答案:

答案 0 :(得分:2)

感谢@wangthony,我查看了http://apidock.com/rails/ActiveRecord/QueryMethods/includes上的includes方法并调整了他们的一个示例,以便让它发挥作用。这是解决方案:

def assign_property
  self.properties = Property.includes(:account_invitations).where('account_invitations.email = ?', self.email).references(:account_invitations)
  self.save
end

答案 1 :(得分:0)

我相信你可以这样做:

user.properties = Property.includes(:account_invitations).where(email: user.email)
user.save