0

我想显示所有发现天的所有价格。

在控制器视图中

def view
 @travel = Travel.find(params[:id])
 @car = Car.find(:first, :conditions => ["id = ?", @travel.car_id])
 @start_day = StartDay.find(:all, :conditions => ["travel_id = ?", @travel.id])
 @import_price = ImportPrice.find(:all, 
        :conditions => ["begin_date = ? and car_code = ?",
                        @start_day.day, @car.short_name])
end

当我添加值 @import_price 出现错误:

undefined method `day' for #<Array:0x7feb70d56fe8> 

我如何为所有日子做出正确的选择?

提前致谢。

红宝石 1.8.7 轨道 2.3

4

4 回答 4

0

是的,因为您的 @start_day 对象正在返回一个数组。如果要获取日期字段数据,可以这样做:

def view
 @travel = Travel.find(params[:id])
 @car = Car.find(:first, :conditions => ["id = ?", @travel.car_id])
 @start_day = StartDay.find(:all, :conditions => ["travel_id = ?", @travel.id])
 @import_price = ImportPrice.find(:all, 
        :conditions => ["begin_date in ? and car_code = ?",
                        @start_day.map{|x| x.day}, @car.short_name])
end

或者

def view
 @travel = Travel.find(params[:id])
 @car = Car.find(:first, :conditions => ["id = ?", @travel.car_id])
 @start_day = StartDay.find(:first, :conditions => ["travel_id = ?", @travel.id])
 @import_price = ImportPrice.find(:all, 
        :conditions => ["begin_date = ? and car_code = ?",
                        @start_day.day}, @car.short_name])
end
于 2013-09-18T08:50:16.557 回答
0

这对你有用吗?

@start_day = StartDay.find(:first, :conditions => ["travel_id = ?", @travel.id], :order => "id DESC")
 @import_price = ImportPrice.find(:all, 
        :conditions => ["begin_date = ? and car_code = ?",
                        @start_day.day, @car.short_name])
于 2013-09-18T08:51:43.947 回答
0

我的回答是;我还借此机会根据您的模型关联(如果它们在那里)稍微重写它:

def view
  @travel = Travel.find(params[:id])
  @car = Car.first.where(:id => @travel.car_id) #@travel.car? I don't know if that will work but it looks like it would
  @start_day = StartDay.where(:travel_id => @travel.id) # wouldn't @travel.start_days work?
  @import_price = ImportPrice.where("begin_date IN (?) and car_code = ?", 
    @start_day.map(&:day), @car.short_name)
end

用于@start_day.map(&:day)获取要查询的所有日期。

于 2013-09-18T09:05:58.983 回答
0

错误原因

StartDay.find(:all, :conditions => ["travel_id = ?", @travel.id])

您收到此错误是因为代码返回您一个满足您条件的所有对象(即数据库表中的所有行)的数组。即使您的数据库表中只有一个条目满足您的条件,返回也将采用数组格式。

解决方案

一种解决方案可以是:

 @start_day = StartDay.find(:first, :conditions => ["travel_id = ?", @travel.id])

另一个解决方案可以是:

@import_price = ImportPrice.find(:all, 
        :conditions => ["begin_date in ? and car_code = ?",
                        @start_day.map{|x| x.day}, @car.short_name])
于 2013-09-18T15:22:43.580 回答