Rails 5 after_create回调创建has_many:通过连接表

时间:2018-05-27 04:17:38

标签: ruby-on-rails ruby-on-rails-5

我的AccountPage模型与has_many :through模型有Campaigns关联。我想要做的是在使用create_after回调创建新页面时创建连接表。

我还与has_many :throughAccount模型建立了User关联。

我得到的当前错误是Account must exist。我想要做的是抓住account_id用户的logged_in,但是时间很艰难。

我在下方包含了所有模型,因此您可以了解最新情况。用户创建帐户,获取激活电子邮件,然后登录。  此时,创建的所有内容都附加到帐户,而不是用户 - 在这种情况下,我想创建一个页面,并让它通过广告系列创建一个与帐户的联接表。

account.rb

class Account < ActiveRecord::Base
  after_create :set_membership
  belongs_to :owner, class_name: 'User'
  accepts_nested_attributes_for :owner

  has_many :memberships
  has_many :users, through: :memberships

  has_many :campaigns
  has_many :pages, through: :campaigns


  # Create Membership
  def set_membership
    user_id = self.owner_id
    Membership.create!(user_id: user_id, account_id: id)
  end
end

user.rb

class User < ApplicationRecord
  has_many :memberships
  has_many :accounts, through: :memberships
  #accepts_nested_attributes_for :accounts

  attr_accessor :remember_token, :activation_token, :reset_token
  before_save :downcase_email
  before_create :create_activation_digest
  before_save {self.email = email.downcase}
  validates :name, presence: true, length: {maximum: 50}
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: {maximum: 255},
            format: {with: VALID_EMAIL_REGEX},
            uniqueness: {case_sensitive: false}
  has_secure_password
  validates :password, presence: true, length: {minimum: 6}, allow_nil: true
  validates :password, presence: true, length: {minimum: 6}
  after_create :send_activation_email

  # Non-Admin User Roles
  enum role: [:standard]
  after_initialize :set_default_role, if: :new_record?

  def set_default_role
    self.role ||= :standard
  end

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
               BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(attribute, token)
    digest = send("#{attribute}_digest")
    return false if digest.nil?
    BCrypt::Password.new(digest).is_password?(token)
  end

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Activates an account.
  def activate
    # update_columns(activated: FILL_IN, activated_at: FILL_IN)
    update_attribute(:activated, true)
    update_attribute(:activated_at, Time.zone.now)
  end

  # Sends activation email.
  def send_activation_email
    UserMailer.account_activation(self).deliver_now
  end

  # Sets the password reset attributes.
  def create_reset_digest
    self.reset_token = User.new_token
    update_attribute(:reset_digest, User.digest(reset_token))
    update_attribute(:reset_sent_at, Time.zone.now)
    # update_columns(reset_digest:  FILL_IN, reset_sent_at: FILL_IN)
  end

  # Sends password reset email.
  def send_password_reset_email
    UserMailer.password_reset(self).deliver_now
  end

  # Returns true if a password reset has expired.
  def password_reset_expired?
    reset_sent_at < 2.hours.ago
  end

  private

  # Converts email to all lower-case.
  def downcase_email
    self.email = email.downcase
  end

  # Creates and assigns the activation token and digest.
  def create_activation_digest
    self.activation_token = User.new_token
    self.activation_digest = User.digest(activation_token)
  end
end

page.rb

class Page < ApplicationRecord
  after_create :set_campaign
  belongs_to :account

  has_many :campaigns
  has_many :accounts, through: :campaigns

  # Create Campaign
  def set_campaign
    Campaign.create!(account_id: account_id, page_id: id)
  end
end

campaign.rb

class Campaign < ApplicationRecord
  belongs_to :account
  belongs_to :page
end

1 个答案:

答案 0 :(得分:0)

在rails after_create中,回调不会在默认数据库策略中关闭事务。因此,当您调用after_create时,实际上数据库中没有记录。 您的案例应该尝试:

after_commit :set_membership, on: :create

或者提供记录而不是id:

def set_membership
  Membership.create!(user_id: owner_id, account: self)
end