我是Rails的初学者,而且我实际上仍然坚持“初学者问题”。
我有一个“声音”脚手架控制器,我不得不添加动作“sendit”。我无法访问从我的视图到控制器的声音。
当我尝试访问“http://127.0.0.1:3000/sounds/sendit.14 ”这是我的错误(为什么它是sendit.14而不是声音/ sendit / 14或声音/ 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
由于Adding an action to an existing controller (Ruby on Rails)
,我在路径文件中执行了此操作
当我执行 rake路由时,这是输出:
[...]
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像其他默认操作一样?如何解决?)
感谢您的帮助
答案 0 :(得分:2)
因为您没有到id为param的操作的路由,所以rails假定id是format 你必须为那个
创建路线resources :sounds do
post :sendit, on: :member
end
答案 1 :(得分:2)
而不是:
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)
希望这能为你做到,...
答案 2 :(得分:1)
您应该在路由中定义id参数,请参阅here。
match "/sounds/:id/sendit/", :controller => "sounds", :action => "sendit"
您可以使用“as”选项命名路线。以上网站的一个例子:
match 'exit' => 'sessions#destroy', :as => :logout
如果你只想要一个get,那么你可以使用get而不是match。一个例子:
或者:
match 'photos/show' => 'photos#show', :via => :get
或更短:
get 'photos/show'