adding optional parameters in paths dynamically ruby on rails

845 views Asked by At

I have routes like this:

resources :lesson_plans do
   resources :videos
end

and also

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

Now I want to create dynamic paths and adding conditional parameters to them.

If I have url like:

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

the path is now:

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

but if I have url like this:

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

the path is:

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

but it should be as its my requirement:

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

the code I am trying is:

Code:

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

Button:

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

Any more better way to cope with it. basically subject_id is what I have optional for both cases.

1

There are 1 answers

3
gabrielhilal On
<%
  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
%>

and then

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