在路径中添加可选参数动态ruby在rails上

时间:2016-12-22 13:18:54

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

我有这样的路线:

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是我对两种情况都可选的。

1 个答案:

答案 0 :(得分:0)

<%
  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" %>