0
votes

I don't know have to get select box for the association and value from the other model. For example i have a table course_names to record course name.

I have other table which has other table course which has more columns with course_name_id

class Course < ActiveRecord::Base

  belongs_to :course_name

end

Now, i have to create student_profile and have association for courses table like this.

class Student < ActiveRecord::Base

  belongs_to :course
  ...
end

And in the view with the simple form i have to create a select box for to select course.

<%= simple_form_for(@student_profile) do |f|%>
    <% f.error_notification %>
    <div class="form-inputs">
        <%= f.association :course  %>

But this association don't show course name.

<select class="select optional form-control" id="student_course_id" name="student[course_id]"><option value=""></option>
<option value="3">#&lt;Course:0x00000105c23818&gt;</option></select>

But i want the output as (course-name for the option from course_names)

<select class="select optional form-control" id="student_course_id" name="student[course_id]">
<option value=""></option>
<option value="3">course-name</option>
</select>

How, do i achieve this. one, solution is

<%= f.association :course,collection:Course.all.includes(:course_name).map{|a|[a.course_name.name,a.id]}  %>

but this doesn't seem right? How do i tell association go get course name from the association.

1

1 Answers

1
votes

have you tried to use this : label_method like that :

<%= f.association :course, label_method: :course_name  %>

Or as course belongs to course_name, maybe you want this:

<%= f.association :course, label_method: lambda { |course| "#{course.course_name.name}"}  %>

Edit To avoid all the queries, you should preload the data

courses = Course.includes(:course_name)

And then use it as follow

<% f.association :course, collection: courses, label_method: lambda { |course| "#{course.course_name.name}" } %>