0

Y.A.N (yet another newbie)

Using rails, I have a 'students' controller and a 'contacts' controller and of course, a student model and contact model. contact belongs_to student and student has_many contacts. I have an index page of students that lists each student with the option to click "Add Contact" for each student. I'm losing it when I try to call the contacts' 'new' action and subsequently the "new" view for contacts. How/where do i initialize the student and/or contact so the contact knows the student_id. Right now, I'm passing the student to the new_contact_path but then I have to refer to the student_Id as params(:format) inside the contact controller in order to get it to work. this is obviously not the best way. Any ideas Pieces of code below:

ContactsController:
def new
    @contact = Contact.new
    @student = Student.find(params[:format])
end

students index:
<% @students.each do |student| %>
  <tr>          
    <td><%= link_to 'Contacts', new_contact_path(student) %></td>
  </tr>
<% end %>
1

2 Answers 2

1

you could pass student_id in the new_contact_path link.

<%= link_to 'Contacts', new_contact_path(student, :student_id => student.id) %>

and in the controller

class ContactsController
  def new
    @student = Student.find(params[:student_id])
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0

When you need to find the student with

@student = Student.find(params[:format])

there is definitely something wrong with your routes.

Your routes should be something like:

resources :students do
  resources :contacts
end

And your code should be:

@student = Student.find(params[:student_id])

The index view you posted should work fine provided you initialised @students properly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.