我在一个控制器中有多个操作,我想在我的一个操作中重用一些代码。所以我决定把它放在一个模型类方法中。遗憾的是,无法在视图中访问返回的变量。在这里你可以看到控制器动作(我调用的模型方法是check_bibip_prices)
def sold_to_winner
@soldcars = Soldcar.winner_username(params[:winnerusername]).order("auctioncarenddate DESC").paginate(:page => params[:page], :per_page => 15)
@page_name = "Cars Sold to: " + params[:winnerusername]
render :index
authorize! :show, @soldcars
@car_buy_prices, @car_sell_prices, @car_status, @car_salesprice_background, @car_winnersalesprice_background = Soldcar.check_bibip_prices(@soldcars)
end
模型可以看作如下:
class Soldcar < ApplicationRecord
belongs_to :bibipprice
scope :isongoingauction, ->(isongoingauction) { where isongoingauction: isongoingauction }
scope :winner_username, ->(winnerusername) { where(winnerusername: winnerusername) }
def self.check_bibip_prices(soldcars)
@car_buy_prices = {}
@car_sell_prices = {}
@car_status = {}
@car_salesprice_background = {}
@car_winnersalesprice_background = {}
@soldcars.each do |car|
if (car.paintbodydamage < 10) and (car.mechanicaldamage < 2)
@car_status[car.carid] = "excellent"
@car_buy_prices[car.carid] = car.bibipprice.dealer_price_three
@car_sell_prices[car.carid] = car.bibipprice.estimated_price_three
elsif (car.paintbodydamage < 18) and (car.mechanicaldamage < 5)
@car_status[car.carid] = "good"
@car_buy_prices[car.carid] = car.bibipprice.dealer_price_two
@car_sell_prices[car.carid] = car.bibipprice.estimated_price_two
else
@car_status[car.carid] = "fair"
@car_buy_prices[car.carid] = car.bibipprice.dealer_price_one
@car_sell_prices[car.carid] = car.bibipprice.estimated_price_one
end
if car.bibipprice.estimated_price_three > 0
if car.winnersalesprice > @car_sell_prices[car.carid]
@car_winnersalesprice_background[car.carid] = "pricealert"
elsif car.winnersalesprice > @car_buy_prices[car.carid]
@car_winnersalesprice_background[car.carid] = "pricesoso"
elsif car.winnersalesprice > 0
@car_winnersalesprice_background[car.carid] = "priceok"
end
if car.salesprice > @car_sell_prices[car.carid]
@car_salesprice_background[car.carid] = "pricealert"
elsif car.salesprice > @car_buy_prices[car.carid]
@car_salesprice_background[car.carid] = "pricesoso"
else
@car_salesprice_background[car.carid] = "priceok"
end
else
@car_salesprice_background[car.carid] = ""
@car_winnersalesprice_background[car.carid] = ""
end
end
return @soldcarscar_buy_prices, @soldcarscar_sell_prices, @soldcarscar_status, @soldcarscar_salesprice_background, @soldcarscar_winnersalesprice_background
end
end
答案 0 :(得分:2)
问题是您在调用render
方法后实例化变量。
将render :index
放在sold_to_winner
方法的底部,它应该有效:
def sold_to_winner
@soldcars = Soldcar.winner_username(params[:winnerusername]).order("auctioncarenddate DESC").paginate(:page => params[:page], :per_page => 15)
@page_name = "Cars Sold to: " + params[:winnerusername]
authorize! :show, @soldcars
@car_buy_prices, @car_sell_prices, @car_status, @car_salesprice_background, @car_winnersalesprice_background = Soldcar.check_bibip_prices(@soldcars)
render :index
end