迭代关联对象

时间:2013-12-08 14:52:32

标签: ruby-on-rails ruby-on-rails-4 erb rails-activerecord

设置了has_many through关系后,我试图在对象A的视图中迭代关联的B对象。

之类的东西
<% for q in @survey.questions do %>
  <%= q.name %> <br/>
<% end %>

没有产生任何结果,而

<%= @survey.questions %>

产量

#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Question:0x007f9859f221e8>

我应该如何(应该)访问这些?


这是控制器

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

这是模特

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

3 个答案:

答案 0 :(得分:0)

试试这个:

<% @survey.questions.each do |q| %>
  <%= q.name %> <br/>
<% end %>

Ruby中应避免使用for循环。从this question开始,看起来循环对数组进行操作,所以这样的东西也可以工作(再次,这不是推荐的解决方案):

<% for q in @survey.questions.to_a do %>
  <%= q.name %> <br/>
<% end %>

更新

我认为你需要在Assignment模型中使你的关联变得单一:

class Assignment < ActiveRecord::Base
  belongs_to :survey
  belongs_to :question
end

我创建了一个您可能会觉得有用的quiz on many to many relationships

答案 1 :(得分:0)

据我所知,鲍尔斯的回答应该有效。尝试检查@survey是否真的有任何问题。在页面<%= @survey.questions.count %>

中添加此内容

答案 2 :(得分:0)

您确定有问题的@survey是否真的有与之相关的作业?你能在Rails控制台上看到它们吗?