使用Connection创建用户模型(友谊)

时间:2016-01-28 20:25:18

标签: ruby-on-rails ruby

我有Retailer和Supplier模型,它继承自User模型。我一直在努力在他们之间建立友谊模型。我希望零售商根据@ suuplier.account_number向供应商发送朋友请求。零售商只有拥有账号才能发送请求。到目前为止,我有请求模型正是这样做。这是我在控制器中的内容,

class RequestsController < ApplicationController
before_action :authenticate_user!

  def new
    @retailer = current_user
    @request = @retailer.requests.new
  end

  def create
   @retailer = current_user
   @supplier = Supplier.find_by(params[:account_number])
   @request = @retailer.requests.new(request_params)
   @request.retailer = current_user
   @request.supplier = @supplier
   if @request.save
     redirect_to  retailer_pending_suppliers_path, notice: "Your request has been successfully sent"
   else
     render 'new'
   end
  end


  private

  def request_params
    params.require(:request).permit(:retailer_id, :supplier_id,:account_number ,:status)
  end

end

它有效,但我仍然100%对我正在做的事情没有信心。这就像一个布洛克墙壁的时刻,不知道现在该做什么。我如何与他们建立友谊?我需要什么型号?和控制器?

提前谢谢。

用户模型

class User < ActiveRecord::Base
  before_validation :generate_account_number
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def role?
    self.class.name.downcase.to_sym
  end

  def admin?
    self.type == "Admin"
  end
  def supplier?
    self.type == "Supplier"
  end
  def retailer?
    self.type == "Retailer"
  end

  def active_for_authentication?
   super && approved?
 end

 def inactive_message
   if !approved?
     :not_approved
   else
     super # Use whatever other message
   end
 end



private
#this method generates and assigns random account number to the users
  def generate_account_number
    rand_num = SecureRandom.hex(3).upcase
    if self.admin?
      self.account_number = "EGYPT" + "-" + rand_num
    elsif self.retailer?
      self.account_number = "NJ" + "-" + rand_num  + "-" + "RET"
    elsif self.supplier?
      self.account_number = "NJ" +"-" + rand_num + "-"  + "SUP"
    else
      self.account_number = 0
    end
  end


end

零售商模型

class Retailer < User
  has_many :stations
  has_many :retailer_suppliers
  has_many :suppliers , through: :retailer_suppliers, as: :connections
  has_many :requests
end

供应商模式

class Supplier < User
  has_many :retailer_suppliers
  has_many :retailers, through: :retailer_suppliers
  has_many :requests
end

请求模型

class Request < ActiveRecord::Base
  belongs_to :retailer
  belongs_to :supplier

  enum status: [:pending, :approved, :denied]
end

我在用户模型中有用户类型属性。

2 个答案:

答案 0 :(得分:0)

您可以拥有类似于属于零售商和供应商的请求模型的友谊模型

class Friendship < ActiveRecord::Base
  belongs_to :retailer
  belongs_to :supplier
end

或者,只需使用请求模型:status =&gt; :批准追踪友谊。
向供应商显示请求,当供应商点击接受按钮时,您可以找到请求和update_attributes,从待处理到批准

答案 1 :(得分:0)

我认为此railscast可能会对您有所帮助:self referential association

但它与海德尔的回应相似。您需要另一个连接表,或修改请求连接表以指示友谊,我猜测将需要存储其他元数据。