【问题标题】:adding optional parameters in paths dynamically ruby on rails在路径中动态添加可选参数 ruby​​ on rails
【发布时间】:2016-12-22 13:18:54
【问题描述】:

我有这样的路线:

resources :lesson_plans do
   resources :videos
end

还有

resources :subjects do
  resources :lesson_plans do
  resources :videos
 end
end

现在我想创建动态路径并向它们添加条件参数。

如果我有这样的网址:

http://localhost:3000/teacher/katherine-fleming/subjects/3/lesson_plans/3

现在的路径是:

http://localhost:3000/teacher/katherine-fleming/subjects/3/lesson_plans
/3/videos/new

但如果我有这样的网址:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans/68

路径是:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans//videos/new.68

但这应该是我的要求:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans/68/videos/new

我正在尝试的代码是:

代码:

<% subject_path = params[:subject_id].present? ? 'subject_' : '' %>
<% subject_var = params[:subject_id].present? ? @subject : '' %>

按钮:

<%= link_to '+ New Video', send("new_teacher_teacher_#
{subject_path}lesson_plan_video_path", @teacher, subject_var, @lesson_plan),
 remote: true, class: "btn btn-info plans-items-btn" %>

有更好的方法来应对它。基本上,subject_id 是我在这两种情况下都可以选择的。

【问题讨论】:

  • get 'teacher/:teacher_id(/:subjects(/:subject_id))/lesson_plans/:lesson_plan_id' =&gt; 'videos#new' - 在你的routes.rb 顶部有这样的东西怎么样?
  • 我试过get 'teacher/:teacher_id(/:subjects(/:subject_id))/lesson_plans/‌​:lesson_plan_id' =&gt; 'videos#new' post 'teacher/:teacher_id(/:subjects(/:subject_id))/lesson_plans/‌​:lesson_plan_id' =&gt; 'lesson_plans#show',它说:ActionController::RoutingError (No route matches [GET] "/teacher/carmel-cynthia/lesson_plans/68"):
  • 我们不能使用资源路由来做到这一点吗?它可能包括近 30 条路由行,用于在路由文件中提供可选参数。有更好的解决方法吗?我有 30 条带和不带 subject_id 的路线。所以而不是制作 60 条线路。我想使用最少的代码行来完成工作。 :)

标签: ruby-on-rails ruby ruby-on-rails-4 routes rails-routing


【解决方案1】:
<%
  path = if params[:subject_id].present?
          new_teacher_subject_lesson_plan_video_path(@teacher, @subject, @lesson_plan)
        else
          new_teacher_lesson_plan_video_path(@teacher, @lesson_plan)
        end
%>

然后

<%= link_to '+ New Video', path, remote: true, class: "btn btn-info plans-items-btn" %>

【讨论】:

  • 感谢您的回答。是的,它可以完成这项工作,但我们不能选择性地在路径中添加参数,还是它有任何限制,不可能的事情?
  • 好吧,当您的 subject_var 为 nil 时,您将发送类似 new_teacher_lesson_plan_video_path(@teacher, nil, @lesson_plan) 的内容,但我认为它不会起作用
  • 感谢您的意见。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2011-10-28
相关资源
最近更新 更多