Having set up a has_many through relationship, I'm trying to iterate through associated B objects in the view of an object A. I.e. something like
<% for q in @survey.questions do %>
<%= q.name %> <br/>
<% end %>
yields nothing, while
<%= @survey.questions %>
yields
#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Question:0x007f9859f221e8>
How could (should) I access these?
Here's the Controller
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
def index
@surveys = Survey.all
end
def show
end
def new
@survey = Survey.new
end
def edit
end
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render action: 'show', status: :created, location: @survey }
else
format.html { render action: 'new' }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @survey.update(survey_params)
format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def destroy
@survey.destroy
respond_to do |format|
format.html { redirect_to surveys_url }
format.json { head :no_content }
end
end
private
def set_survey
@survey = Survey.find(params[:id])
end
end
And here's the Models
class Survey < ActiveRecord::Base
has_many :assignments
has_many :questions, through: :assignments
end
.
class Question < ActiveRecord::Base
has_many :assignments
has_many :surveys, through: :assignments
end
.
class Assignment < ActiveRecord::Base
belongs_to :survey
belongs_to :question
end