如何在没有任何参数的情况下调用 "show" 方法?
How do I call my "show" method without any parameters?
我的 routes.rb 文件中有这个
resources :votes
当我 运行 耙路线时,它给出
votes GET /votes(.:format) votes#index
POST /votes(.:format) votes#create
new_vote GET /votes/new(.:format) votes#new
edit_vote GET /votes/:id/edit(.:format) 投票#edit
投票 GET /votes/:id(.:format) votes#show
我的问题是如何在没有任何参数的情况下调用我的“/show”方法?如果有人不提供 ID,我想使用此控制器方法生成随机结果
def show
id = params[:id]
# If there is no person selected based on the param, choose one randomly
if !id.present?
if current_user
@person = Person.joins("LEFT JOIN users ON users.id = people.user_id")
.where("people.user_id IS NULL")
.order("RANDOM()").limit(1).first
end
if @person.nil?
@person = Person.order("RANDOM()").limit(1).first
end
else
@person = Person.find_by_id(id)
if current_user
@vote = Vote.where(person_id: id, user_id: current_user.id).first || Vote.new
end
end
end
但是现在当我在浏览器中输入“/votes”时,它因错误而死掉了
The action 'index' could not be found for VotesController
您不能,至少当您使用 resources
时 — resources
生成一组遵循 RESTful 实践的标准路由。在您的情况下,它正在生成 get '/votes/:id', to: 'votes#show'
因为没有匹配的参数,它假定您正试图去 votes#index
如果你想匹配两者,我会在你的 routes.rb
中做这样的事情:get '/votes(/:id)', to: 'votes#show'
parens 表示可选参数。您可能需要将此放在 resources
块之前,或者更改 resources
块以省略 show
操作。
关于参数的更多信息:http://guides.rubyonrails.org/v5.1.1/routing.html#bound-parameters
我的 routes.rb 文件中有这个
resources :votes
当我 运行 耙路线时,它给出
votes GET /votes(.:format) votes#index
POST /votes(.:format) votes#create
new_vote GET /votes/new(.:format) votes#new
edit_vote GET /votes/:id/edit(.:format) 投票#edit 投票 GET /votes/:id(.:format) votes#show
我的问题是如何在没有任何参数的情况下调用我的“/show”方法?如果有人不提供 ID,我想使用此控制器方法生成随机结果
def show
id = params[:id]
# If there is no person selected based on the param, choose one randomly
if !id.present?
if current_user
@person = Person.joins("LEFT JOIN users ON users.id = people.user_id")
.where("people.user_id IS NULL")
.order("RANDOM()").limit(1).first
end
if @person.nil?
@person = Person.order("RANDOM()").limit(1).first
end
else
@person = Person.find_by_id(id)
if current_user
@vote = Vote.where(person_id: id, user_id: current_user.id).first || Vote.new
end
end
end
但是现在当我在浏览器中输入“/votes”时,它因错误而死掉了
The action 'index' could not be found for VotesController
您不能,至少当您使用 resources
时 — resources
生成一组遵循 RESTful 实践的标准路由。在您的情况下,它正在生成 get '/votes/:id', to: 'votes#show'
因为没有匹配的参数,它假定您正试图去 votes#index
如果你想匹配两者,我会在你的 routes.rb
中做这样的事情:get '/votes(/:id)', to: 'votes#show'
parens 表示可选参数。您可能需要将此放在 resources
块之前,或者更改 resources
块以省略 show
操作。
关于参数的更多信息:http://guides.rubyonrails.org/v5.1.1/routing.html#bound-parameters