Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating through associated objects
    primarykey
    data
    text
    <p>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</p> <pre><code>&lt;% for q in @survey.questions do %&gt; &lt;%= q.name %&gt; &lt;br/&gt; &lt;% end %&gt; </code></pre> <p>yields nothing, while</p> <pre><code>&lt;%= @survey.questions %&gt; </code></pre> <p>yields</p> <pre><code>#&lt;ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Question:0x007f9859f221e8&gt; </code></pre> <p>How could (should) I access these?</p> <hr> <p>Here's the Controller</p> <pre><code>class SurveysController &lt; 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 </code></pre> <hr> <p>And here's the Models</p> <pre><code>class Survey &lt; ActiveRecord::Base has_many :assignments has_many :questions, through: :assignments end </code></pre> <p>.</p> <pre><code>class Question &lt; ActiveRecord::Base has_many :assignments has_many :surveys, through: :assignments end </code></pre> <p>.</p> <pre><code>class Assignment &lt; ActiveRecord::Base belongs_to :survey belongs_to :question end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload