0

嗨,我需要幫助和所有見解。我有兩個模型拍賣和投標,我想取回所有拍賣CURRENT_USER贏了,他/她已經被競價超過的那些和那些他/她就是贏得跨2個模型的聯合查詢(has_many)

這裏有兩種型號:

class Auction < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :guid, use: :slugged 
    before_save :populate_guid 
    mount_uploaders :images, ImageUploader 
    belongs_to :client 
    has_many :bids, dependent: :destroy 
    has_one :order, dependent: :destroy 
    validates_presence_of :title, :lien_price, 
        :end_time, :collateral_value, 
        :redemption_date, :current_interest_rate, 
        :additional_tax, :collateral_details, 
        :location, :client_id, :starting_bid 
    validate :end_time_in_the_future, :on => :update 
    validates_uniqueness_of :guid, case_sensitive: false 
    def end_time_in_the_future 
    errors.add(:end_time, "can't be in the past") if self.end_time && self.end_time < Time.now 
    end 
    def self.get_active_auctions 
    where("end_time > ?", Time.now) 
    end 
    def self.closed_auctions 
    where("end_time < ?", Time.now) 
    end 
    def highest_bid 
    self.bids.maximum("amount") 
    end 
    def highest_bid_object 
    self.bids.order(:amount => :desc).limit(1).first 
    end 
    def highest_bidder 
    self.highest_bid_object.user if highest_bid_object 
    end 
    def closed? 
    self.end_time < Time.now 
    end 
    private 
    def populate_guid 
    if new_record? 
     while !valid? || self.guid.nil? 
     self.guid = SecureRandom.random_number(1_000_000_000).to_s(36) 
     end 
    end 
    end 
end 

class Bid < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :guid, use: :slugged 
    belongs_to :auction 
    belongs_to :user 
    before_save :populate_guid 
    validates_presence_of :amount, :user_id, 
        :auction_id 

#validate :higher_than_current? 
validates :amount, :numericality => true 
validates_uniqueness_of :guid, case_sensitive: false 
def higher_than_current? 
    if !Bid.where("amount > ? AND auction_id = ?", amount, self.auction.id).empty? 
    errors.add(:amount, "is too low! It can't be lower than the current bid, sorry.") 
    end 
end 
private 
    def populate_guid 
    if new_record? 
     while !valid? || self.guid.nil? 
     self.guid = SecureRandom.random_number(1_000_000_000).to_s(36) 
     end 
    end 
    end 
end 

我想

@auctions = Auction.closed_auctions.where(highest_bidder: current_user) 

@auctions = Auction.closed_auctions.joins(:bids).where(highest_bidder: current_user) 

會工作,但他們都會產生錯誤。

編輯這個工作

@auctions = Auction.closed_auctions.references(highest_bidder: current_user) 

,不過也許有一個更好的辦法。

回答

0

您可能無法從控制器訪問current_user(設計?)。所以您需要將用戶作爲參數傳遞給類或實例方法。你應該看看什麼是範圍,特別是接受參數的範圍。範圍可以真正幫助您重構您的拍賣模型(您實際上不需要任何僅返回where())的方法,而且還可以解決無法訪問的current_user。

使用它像這樣在您的競價模式:

scope: :highest_bidder -> (current_user) { where(highest_bidder: current_user) } 

從你的控制器這樣稱呼它:

@auctions = Auction.closed_auctions.highest_bidder(current_user)