【问题标题】:Ruby on Rails - Creating a route for a custom viewRuby on Rails - 为自定义视图创建路由
【发布时间】:2013-12-09 22:25:09
【问题描述】:

我觉得我已经很接近了,所以我会直奔主题。我创建了一个新的视图文件 (app/views/subjects/screening.html.erb)。这会将新文件放在我用作模板的 edit.html.erb 旁边。我的 edit.html.erb 文件按预期工作,这真的很奇怪,因为我已经为我的新文件复制了逻辑/路由/等,但我没有得到相同的结果。

这令人沮丧。 MVC 很刻薄。

所以这里是页面的链接:

主题/index.html.erb

  <% @subjects.each do |sub| %>
    <tr>
      <td><%= link_to "edit", edit_subject_path(sub) %></td>
      <td><%= link_to "scr", screening_path(sub) %></td>
      <td><%= sub.subject_id %></td>
      <td><%= sub.study_site == 1? "Seattle" : sub.study_site == 2? "Portland" : "nil"%></td>
      <td><%= sub.treatment_group %></td>
    </tr> 
  <% end %>

“编辑”链接有效,生成此 URL 'localhost:3000/subjects/{:id}/edit'。并且“scr”的链接没有,产生 'localhost:3000/screening.{:id}'。

routes.rb

  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  # resources :subjects, only: [:new, :create, :destroy]
  resources :subjects



  match '/signup', to: 'users#new'
  match '/signin', to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete
  match '/edit', to: 'users#edit'

  root to: 'static_pages#home'

  match '/help', to: 'static_pages#help'
  match '/about', to: 'static_pages#about'
  match '/contact', to: 'static_pages#contact'

  match '/subjects', to: 'subjects#show'
  match '/newsubject', to: 'subjects#new'
  match '/subjects', to: 'subjects#index'
  match '/showsubject', to: 'subjects#show'
  match '/editsubject', to: 'subjects#edit'
  match '/screening', to: 'subjects#screening'

我是否必须声明一些额外的东西,因为我是手动添加的?任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: ruby-on-rails erb rails-routing custom-routes


    【解决方案1】:

    我会建议这样的嵌套路由:

    resources :subjects do 
      match '/screening', to: 'subjects#screening', as: :screening
    end
    

    这应该允许:

    link_to "scr", subject_screening_path(sub)
    #> /subjects/1/screening
    

    我可能对命名有点不满意。请务必检查您的路线(rake routes 在 shell 中)。另外,删除:

      match '/subjects', to: 'subjects#show'
      match '/newsubject', to: 'subjects#new'
      match '/subjects', to: 'subjects#index'
      match '/showsubject', to: 'subjects#show'
      match '/editsubject', to: 'subjects#edit'
      match '/screening', to: 'subjects#screening'
    

    这些路由是使用resources :subjects 自动生成的,但默认情况下它们的路径不同。

    【讨论】:

    • 感谢您的回复。当我尝试加载索引页面时,我得到“未定义的方法“screening_subject_path(sub)””。我正在使用命名约定,但到目前为止我还没有找到让它工作的方法。另外,感谢您提供有关其他路线的提示。
    • @IanEllis 您需要运行rake routes 以确定该路线的确切名称。可能是subject_screening_path。我总是与嵌套路由混淆。
    • 非常感谢您的帮助。这就是问题所在。我刚刚开始掌握这些路线的窍门。
    • @IanEllis 很高兴听到!
    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2011-12-27
    • 2012-06-26
    相关资源
    最近更新 更多