[英]Rails respond_to format HTML Json Not workng with params
我正在创建一个Rails-Angularjs RESTful应用程序。 Rails控制器索引操作需要为Angularjs前端生成一个json。 索引操作接收一个参数,该参数必须用作对数据库的查询中的过滤器。 如果我不使用参数,那么一切正常都会显示结果。 但是,如果我将接收到的参数添加到查询中,它将无法正常工作。
使用查询中的参数的操作索引:def index @project_id = params [:project_id] @tickets = PrintingTicket.where(project_id:@project_id)
respond_to do |format|
format.html
format.json { render json: @tickets }
end
end
这是不使用参数过滤查询中信息的操作索引:
def index
@project_id = params[:project_id]
@tickets = PrintingTicket.all
respond_to do |format|
format.html
format.json { render json: @tickets }
end
end
我注意到index操作执行了两次,一次用于HTML,一次用于JSON。 Project_id的第一轮有效信息有效,第二轮广告为“ nil”。
通过观察控制台,在两种情况下,它都在开头显示参数Parameters: {"project_id"=>"5982a8799f911d0318054997"}
但是,在我使用该参数的情况下,该参数的末尾为“ nil”,例如您可以在日志中看到:
Started GET "/projects/5982a8799f911d0318054997/tickets" for ::1 at 2017-11-18 21:50:34 -0800
Processing by TicketsController#index as HTML
Parameters: {"project_id"=>"5982a8799f911d0318054997"}
Rendered tickets/index.html.erb within layouts/application (0.1ms)
MONGODB | localhost:27017 | ticketmongo_development.find | STARTED | {"find"=>"users", "filter"=>{"_id"=>BSON::ObjectId('595f189d9f911d0518244d9b')}, "limit"=>1, "singleBatch"=>true}
MONGODB | localhost:27017 | ticketmongo_development.find | SUCCEEDED | 0.0019340000000000002s
MONGODB | localhost:27017 | ticketmongo_development.find | STARTED | {"find"=>"companies", "filter"=>{"_id"=>BSON::ObjectId('596059589f911d047bd195bf')}}
MONGODB | localhost:27017 | ticketmongo_development.find | SUCCEEDED | 0.001964s
Rendered companies/_company.html.erb (3.5ms)
Rendered projects/_projects.html.erb (0.5ms)
Rendered layouts/_topmenusignin.html.erb (7.1ms)
Completed 200 OK in 120ms (Views: 106.0ms)
Started GET "/tickets/index/tickets.json" for ::1 at 2017-11-18 21:50:34 -0800
Processing by TicketsController#index as JSON
Parameters: {"id"=>"tickets"}
MONGODB | localhost:27017 | ticketmongo_development.find | STARTED | {"find"=>"printing_tickets", "filter"=>{"project_id"=>nil}}
MONGODB | localhost:27017 | ticketmongo_development.find | SUCCEEDED | 0.0016179999999999999s
Completed 200 OK in 4ms (Views: 3.1ms)
任何帮助都将受到好评!
GET "/projects/5982a8799f911d0318054997/tickets"
正如您从rake routes
看到的那样, tickets#index
操作的路径为/projects/:project_id/tickets
并且您正在将parameters[:project_id]
传递为5982a8799f911d0318054997
。 如果要传递其他参数,则它们将位于request.body
GET "/tickets/index/tickets.json"
这条路线没有意义。 您需要检查路由器,因为它正在使用parameters[:id] = 'tickets
',也许您设置的路由不正确。
现在看起来像这样
GET '/tickets/index/:id'
当您执行GET request
到url /tickets/index/tickets.json
,它将把您最后输入的tickets
作为id
参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.