在Rails中有一个问题,我已经在URL中传递了一些传递参数的路由。
#routes.rb
root 'day#show'
get '/day/:date/:activity' => 'day#show'
get '/day/:date' => 'day#index'
我制作的日控制器如下
#day_controller.rb
class DayController < ApplicationController
def show
if(!params.has_key?(:date))
@date = getCurrentDate()
else
@date = splitDate(params(:date))
end
@days = Day.where("year = ? AND month = ? AND date = ?",@date[0],@date[1],@date[2])
if(params.has_key?(:type))
@activity = getAllData(params(:type))
end
end
def index
@date = params(:date)
if(@date[0] == "?")
@days = Day.all
elseif(@date[1] == "?")
@days = Day.where("year = ?",@date[0])
elseif(@date[2] == "?")
@days = Day.where("year = ? AND month = ?",@date[0],@date[1])
end
end
private
def getCurrentDate
date = DateTime.now.to_s
dateArrayOne = date.split('T')
dateArrayTwo = dateArrayOne[0].split('-')
end
def splitDate(date)
finaldate = date.split('-')
end
def getAllData(type)
dataHash = {}
case type
when "calories"
@days.each do |day|
dataHash[:day.date] = day.calories
end
when "steps"
@days.each do |day|
dataHash[:day.date] = day.steps
end
when "activeMinutes"
@days.each do |day|
dataHash[:day.date] = day.activeMinutes
end
when "distance"
@days.each do |day|
dataHash[:day.date] = day.distance
end
else
@days.each do |day|
dataHash[:day.date] = day.calories
dataHash[:day.date] = day.steps
dataHash[:day.date] = day.activeMinutes
dataHash[:day.date] = day.distance
end
end
dataHash
end
end
因此,每当我输入任何带有日期或活动参数的URL(根很好,因为它只是得到当前日期),我得到错误:
DayController中的ArgumentError #index:错误的参数个数(1个用于 0)在app / controllers / day_controller.rb:15:在'index'
参数正在传递,如其列出的例外页面所示:
Request Parameters: {"date"=>"2015-03-01"}
所以通过这一切我有几个问题......
请给我任何反馈,我对Rails很新,并乐于学习如何改进我的结构。对于凌乱的代码也很抱歉,我没有太多时间重构或评论太多。
答案 0 :(得分:3)
您应该使用params[:date]
代替params(:date)
。它就像一个哈希,而不是一个函数。
如果它是一个处理POST数据的动作,json输入的格式如下:
{ "day": { "date": [2015, 3, 15], "activity": "running" } }
params.require(:day)
可以访问内部哈希,因此params.require(:day).permit(:date, :activity)
可以访问这些值。你可以这样使用它:
def index
if day_params[:date] //not params[:date], which would raise an error
@date = day_params[:date]
if(@date[0] == "?")
@days = Day.all
elseif(@date[1] == "?")
@days = Day.where("year = ?",@date[0])
elseif(@date[2] == "?")
@days = Day.where("year = ? AND month = ?",@date[0],@date[1])
end
end
end
private
def day_params
params.require(:day).permit(:date, :activity)
end
作为一个完全独立的问题,dataHash[:day.date]
将不起作用。这将在符号date
上调用:day
方法,该方法不存在。您可能想要使用dataHash[:day].date
。
答案 1 :(得分:-1)
如果您使用的是Rails 4,则需要strong parameters:
private
def day_params
params.require(:day).permit(:date)
end
然后你可以做类似的事情:
def index
if params[:date]
@date = params[:date]
if(@date[0] == "?")
@days = Day.all
elseif(@date[1] == "?")
@days = Day.where("year = ?",@date[0])
elseif(@date[2] == "?")
@days = Day.where("year = ? AND month = ?",@date[0],@date[1])
end
end
end
P.S。我不确定您是否复制和粘贴,但请考虑使用proper indentation convention。