【问题标题】:what is the best association for a campaign model?竞选模式的最佳关联是什么?
【发布时间】:2014-12-13 03:10:00
【问题描述】:

我是 Rails 的新手,仍然有关联的想法,请在我的试用项目中,我想做一个竞选系统,人们会承诺投票,但不知道如何处理这个关联以获取用户推荐。 应用逻辑 用户只能质押一次,并且在质押过程中他必须选择他的推荐人也是用户。我如何调用用户对象并要求所有都是推荐? 型号:

class User < ActiveRecord::Base
  has_one :pledge

  has_secure_password

  VALID = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

  validates :email, format: { with: VALID , on: :create }
  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates_presence_of [:email, :first_name, :last_name, :phone_number, :gender ]
  validates_uniqueness_of :email




  def signing_counter
    increment! :sign_in_count
  end


end

class Pledge < ActiveRecord::Base
  belongs_to :user
  validates_acceptance_of :agreed
  validates_presence_of :commitment, :user_id
end

提前谢谢...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 associations


    【解决方案1】:
    class Refs < ActiveRecord::Base
        belongs_to :user
        belongs_to :referal, :class_name => 'User'
    end
    
    class User < ActiveRecord::Base
        has_many :refs
        has_many :referals, :through => :refs, :source => :referal
        has_many :refers, :through => :refs, :source => :user
    end
    

    【讨论】:

      【解决方案2】:

      生成用户模型:

      rails g migration user name:string refer_id:integer
      

      单个用户可以引用多个用户 一位用户仅由一位用户推荐/注册。

      #user.rb
      class User < ActiveRecord::Base
          has_many :refers, class_name: 'User', foreign_key: 'refer_id'
          belongs_to :referred_by, class_name: 'User', foreign_key: 'refer_id'
      end
      

      查询:

      #gives the list of users to whom this first User refers.
      User.first.refers 
      #gives the user who has referred the first User.
      User.first.referred_by
      

      【讨论】:

      • 我在运行时遇到了这个问题:User.last.refers User Load (2.3ms) SELECT users.* FROM users ORDER BY users.id DESC LIMIT 1 用户负载 (1.6ms) SELECT users.* FROM users WHERE users.refer_id = 7 Mysql2::Error: Unknown column 'users.refer_id' in 'where 子句': SELECT users。 * FROM users WHERE users.refer_id = 7 ActiveRecord::StatementInvalid: Mysql2::Error: 'where 子句'中的未知列'users.refer_id': SELECT users.* FROM users WHERE @ 987654338@.refer_id = 7
      • 可能您将现有代码与我的代码混淆了。在一个全新的示例示例中尝试我的代码。这将起作用:)
      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2010-09-18
      • 2014-02-27
      相关资源
      最近更新 更多