How to create record with the same id as a parent record from a table in rails

时间:2016-04-04 16:58:43

标签: ruby-on-rails

Im trying to create a system where a teacher can create a lesson, and the student inputs an answer. I have a table cycling through each lesson like this:

<h1>Listing Courses</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @learns.each do |learn| %>
      <tr>
        <td><%= link_to learn.title, new_lesson_path %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Learn', new_learn_path %>

What I need is a way to create a new model record (the new model is Lesson, the old one is Learn) that has a user_id(already figured out) and a learn_id(the one in question). Does anyone know how to give the lesson_id the value of the lesson that was clicked on?

Sorry if this was confusing, and thanks :)

1 个答案:

答案 0 :(得分:0)

You can pass additional parameters in urls:

new_lesson_path(learn_id: learn.id)

and then get it from params[:learn_id] in controller's new action

The more elegant way is to use a nested resource.

resources :learns do
  resources :lessons, shallow:true
end

so that your url will be like /learns/123/lessons/new, helper like new_learn_lesson_path(learn) and still :learn_id in params