我希望显示所有发现日的所有价格。
控制器视图中的
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>
我如何正确选择所有日子?
提前致谢。
ruby 1.8.7 rails 2.3
答案 0 :(得分: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
答案 1 :(得分: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])
答案 2 :(得分: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)
获取您要查询的所有日期。
答案 3 :(得分: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])