什么是广告系列模型的最佳关联?

时间:2014-12-13 03:10:00

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

我是铁杆新手,仍然有协会思考,请在我的试用项目中我想做一个竞选系统,人们会保证投票但不知道如何处理这种关联以取回用户转介。    应用逻辑 用户只能承诺一次,在承诺过程中,他必须选择他也是用户的推荐人。如何调用用户对象并询问所有是推荐?    型号:

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

提前感谢...

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

生成用户模型:

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
相关问题