簡體   English   中英

使控制器動作與傳遞的參數一起正常工作的正確路線-Rails

[英]Proper route to get controller action to work properly with passed argument - Rails

Rails 4.2.1
Ruby 2.1.5

在我的routes.rb中,我有:

get '/activate_test_set' =>  'test_sets#activate_test_set'

在test_sets_controller.rb中,我有:

def activate_test_set test_set
  test_set.update_attribute(status: 'active')
  render test_sets_url
end

在我的views / test_sets / index.html中,我有:

<%= link_to "#{t('activate')}", activate_test_set_path(test_set) %>

在視圖中時,如果單擊鏈接,則會在開發錯誤日志中得到以下內容:

Started GET "/activate_test_set.1" for ::1 at 2016-01-01 13:23:55 -0800
Processing by TestSetsController#activate_test_set as 
Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms)

ArgumentError (wrong number of arguments (0 for 1)):
 app/controllers/test_sets_controller.rb:69:in `activate_test_set'

什么是正確的routes.rb聲明才能正常工作?

我也在routes.rb中嘗試了這個:

get '/activate_test_set/:id' =>  'test_sets#activate_test_set'

這就是我得到的:

Started GET "/activate_test_set.1" for ::1 at 2016-01-01 15:14:57 -0800
    SELECT `schema_migrations`.* FROM `schema_migrations`
ActionController::RoutingError (No route matches [GET] "/activate_test_set.1"): 

解:

經過一些額外的實驗,這就是我解決此問題的方法。 作為一個新手,我不確定這是否是最好的解決方案,但是在這里:

match "activate_test_set/:id", :to => "test_sets#activate_test_set", :as => :activate_test_set, via: [:get]

嘗試在注釋中建議的內容:

更改get '/active_test_set'...get '/active_test_set/:id'

另一種方法是使用普通參數,在這種情況下,您需要:

將鏈接標記更改為: <%= link_to "#{t('activate')}", activate_test_set_path(id: test_set) %>

無論選擇哪種路由修復,在控制器操作中都不需要參數。 每當您的控制器動作與路由一起使用時,您都不需要該動作的參數,而是在link標簽中設置參數(如Fix 2中所示),然后通過控制器動作內部的params hash訪問它們,如下所示:

def activate_test_set
  test_set = TestSet.find(params[:id])
  test_set.update_attribute(status: 'active')
  render test_sets_url
end 

編輯:使用rake routes以查看該操作的鏈接方法。

在路線中,您想要設置一個參數

get '/activate_test_set/:id' =>  'test_sets#activate_test_set'

然后,當您鏈接到它時,它將test_set_id添加到params哈希中,您將可以像這樣獲取它

def activate_test_set
  test_set = TestSet.find(params[:id])
  test_set.update_attribute(:status, 'active')

  ...

end

另請注意,此錯誤

Started GET "/activate_test_set.1" for ::1 at 2016-01-01 13:23:55 -0800

.1是format (默認為html)。 將test_set作為參數發送時,它將test_set的ID作為格式放入url中。 當您看到此內容時,幾乎始終不是您想要的。 當您將太多參數傳遞給path方法時,就會發生這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM