[英]Couldn't find Sound without an ID - Stuck Ruby On Rails
我是Rails的初學者,而我實際上顯然陷入了“初學者問題”。
我有一個“聲音”支架式控制器,我必須添加一個動作“ sendit”。 我無法從我的視圖訪問控制器的聲音。
當我嘗試訪問“ http://127.0.0.1:3000/sounds/sendit.14 ”時,這是我的錯誤(為什么是sendit.14而不是sounds / sendit / 14或sounds / 14 / sendit?)
ActiveRecord::RecordNotFound in SoundsController#sendit
Couldn't find Sound without an ID
Application Trace | Framework Trace | Full Trace
app/controllers/sounds_controller.rb:74:in `sendit'
Request
Parameters:
{"format"=>"14"}
這是我的代碼:
聲音控制器:
def sendit
@sound = Sound.find(params[:id]) # ----- Error is on this line -----
# Do Job
end
Index.html.erb
<% @sounds.each do |sound| %>
<% if sound.user_id == current_user.id %>
<tr>
<td><%= sound.title %></td>
<td><%= sound.user.email %></td>
<td><%= link_to 'Show', sound %></td>
<td><%= link_to 'Edit', edit_sound_path(sound) %></td>
<td><%= link_to 'Destroy', sound, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Send', sounds_sendit_path(sound) %></td>
的routes.rb
devise_for :users
match "/sounds/sendit/", :controller => "sounds", :action => "sendit"
resources :users, :sounds
我在路由文件中執行此操作是因為將操作添加到現有控制器(Ruby on Rails)
當我做耙路線時 ,這是輸出:
[...]
sounds_sendit /sounds/sendit(.:format) sounds#sendit
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sounds GET /sounds(.:format) sounds#index
POST /sounds(.:format) sounds#create
new_sound GET /sounds/new(.:format) sounds#new
edit_sound GET /sounds/:id/edit(.:format) sounds#edit
sound GET /sounds/:id(.:format) sounds#show
PUT /sounds/:id(.:format) sounds#update
DELETE /sounds/:id(.:format) sounds#destroy
root / home#index
(我實際上不明白第一行,為什么沒有POST / GET,為什么像其他默認操作一樣是sounds_sendit和sendit_sound?如何解決?)
謝謝您的幫助
因為您沒有將id用作參數的操作的路由,所以rails假定id為format您必須為此創建路由
resources :sounds do
post :sendit, on: :member
end
代替這個:
match "/sounds/sendit/", :controller => "sounds", :action => "sendit"
用這個:
resources :sounds do
member do
get :sendit
end
end
然后,您將能夠使用sendit_sound_path
幫助器正確鏈接到操作:
link_to "link text", sendit_sound_path(sound_object)
希望這對您有幫助...
您應該在路由中定義id參數,請參見此處 。
match "/sounds/:id/sendit/", :controller => "sounds", :action => "sendit"
您可以使用“ as”選項來命名路線。 來自上述站點的示例:
match 'exit' => 'sessions#destroy', :as => :logout
如果只想獲取,則可以使用get代替match。 一個例子:
之一:
match 'photos/show' => 'photos#show', :via => :get
或更短:
get 'photos/show'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.