0

(データベースからランダムなアイテムを選択し、それをさらに渡すことができるようにするのに、何日も苦労しています。)

これは基本的な操作であり、いくつかの方法をすべて試しましたが、同じ問題に遭遇しました。params {"id" = "random"} <-コントローラーメソッドの名前

コントローラ:

def random      # method works  checked it in the console. Returns a valid obj.
  @task = Task.find(rand(Task.first.id..Task.last.id))
  render "random"
end

random.html.erb <%= @task %> # 動作させたいです。手動で渡すと #say../random/1例として動作すると、オブジェクトのメモリ #location が表示されます。

エラーログ:

 ActionController::ActionControllerError in TasksController#show
Cannot redirect to nil!

Rails.root: /home/bogdan/ex/bored
Application Trace | Framework Trace | Full Trace

actionpack (3.2.3) lib/action_controller/metal/redirecting.rb:60:in
`redirect_to'
actionpack (3.2.3) lib/action_controller/metal/flash.rb:25:in
`redirect_to'
actionpack (3.2.3) lib/action_controller/metal/instrumentation.rb:60:in
`block in redirect_to'
activesupport (3.2.3) lib/active_support/notifications.rb:123:in `block
in instrument'
activesupport (3.2.3)
lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.3) lib/active_support/notifications.rb:123:in
`instrument'
actionpack (3.2.3) lib/action_controller/metal/instrumentation.rb:59:in
`redirect_to'
actionpack (3.2.3) lib/action_controller/metal/implicit_render.rb:4:in
`send_action'
actionpack (3.2.3) lib/abstract_controller/base.rb:167:in
`process_action'
.
.
.
(only the top of the stack)

Request

Parameters:

{"id"=>"random"}

編集:退屈::Application.routes.draw do

roots.rb :

  to => 'tasks#main'   
  resources :tasks
  match ':controller(/:action(/:id))(.:format)'
4

1 に答える 1

0

ルートが安らかで、リソースに GET がある場合、ID が必要です。コレクションに対して GET を実行する場合、その必要はありません。ランダムが次のようになるようにします

resources :tasks do
  get 'random', :on => :collection
end
于 2012-09-17T17:00:34.440 に答える