0

I would like to know how would you display the values of multiple checkboxes in a view? Below is an example of what am talking about.

<% ExamPaper.all.each do |key, val| %>
    <%= f.check_box :exam_type, {:multiple => true}, key.exam_name, :class => 'exam_type'%>
    <%= key.exam_name %> 
<% end %>

In my view i tried displaying the items that were saved in the database like this;

<%= exam.exam_type %>

and nothing is shown. How would i display the saved items in a rails view?

Thanks..

2 Answers 2

1

ExamPaper.all.each will allow you to loop over instances of ExamPaper rather than a |key, val| pair. It's not entirely clear whether you want to loop over exam papers or some other class called ExamType to select a type for the papers.

My guess is you want something closer to:

<% ExamPaper.all.each do |paper| %>
  <%= f.check_box :exam_type, { :multiple => true, :class => 'exam_type' }, paper.id %>
  <%= paper.name %> 
<% end %>

Assuming that your exam_papers have a name and an id attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Shadwell. The values of ExamPaper are saved by another model Exam. It's in the Exam view where i want to display the multiple exam_types chosen by a user. As in <%= @exam.exam_type %> which shows nothing.
Will write an answer to help (I think)
0

It's in the Exam view where I want to display the multiple exam_types chosen by a user

This is really about ActiveRecord Associations:

#app/models/user.rb
Class User < ActiveRecord::Base
    has_many :exam_types
    has_many :exams, through: :exam_types
end

#app/models/exam.rb
Class Exam < ActiveRecord::Base
    has_many :exam_types
    has_many :users, through: :exam_types
end

#app/models/exam_types.rb
Class ExamType < ActiveRecord::Base
    belongs_to :exam
    belongs_to :user
end

#app/controllers/exams_controller.rb
def show
   @exam = current_user.exams.find(params[:id])
end

#app/views/exams/show.html.erb
<% @exam.exam_types.each do |exam_type| %>
    <%= exam_type %>
<% end %>

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.