[英]Ruby on rails accessing associations
I'm learning Ruby and just struggling to get my head round associations properly. 我正在学习Ruby,并且正努力使自己的头颅关联正确。
I have questions
, sections
, and then a question_sections
table which links the two. 我有
questions
, sections
,然后是将两者链接在一起的question_sections
表。 A question can belong to multiple sections, and a section can have many questions. 一个问题可以属于多个部分,一个部分可以包含许多问题。 Each question is given a
weight
and an order
per section (which is stored in the question_sections
table). 每个部分都有一个
weight
和order
(存储在question_sections
表中)。
Here are my controllers: 这是我的控制器:
class Question < ActiveRecord::Base
has_many :sections, :through => :question_sections
belongs_to :section
has_many :question_sections
default_scope { order(order: :asc) }
accepts_nested_attributes_for :section, :reject_if => :all_blank, allow_destroy: true
accepts_nested_attributes_for :question_sections, :reject_if => :all_blank, allow_destroy: true
end
class Section < ActiveRecord::Base
has_many :questions, :through => :question_sections
has_many :question_sections
has_many :feedbacks
accepts_nested_attributes_for :feedbacks, :reject_if => :all_blank, :allow_destroy => true
end
class QuestionSection < ActiveRecord::Base
belongs_to :section
belongs_to :question
accepts_nested_attributes_for :section, :reject_if => :all_blank, allow_destroy: true
accepts_nested_attributes_for :question, :reject_if => :all_blank, allow_destroy: true
end
I want to be able to access the data in the question_sections table from showing the questions. 我希望能够通过显示问题来访问question_sections表中的数据。
In my 'show' for questions I have: 在我的“表演”中,我有以下问题:
<%= @question.question %>
<%= @question.question_section.weight %>
But i'm getting: 但我得到:
undefined method `question_section' for #<Question:0x007fda20c72cc8>
Any advice on what I'm doing wrong would be really appreciated. 任何关于我做错事的建议都将不胜感激。
First of all, change the below code: 首先,更改以下代码:
class Question < ActiveRecord::Base
has_many :sections, :through => :question_sections
has_many :question_sections
default_scope { order(order: :asc) }
accepts_nested_attributes_for :section, :reject_if => :all_blank, allow_destroy: true
accepts_nested_attributes_for :question_sections, :reject_if => :all_blank, allow_destroy: true
end
& for accesssing data , use <%= @question.question_sections.first.weight %>
&要访问数据,请使用
<%= @question.question_sections.first.weight %>
This is because question sections is an array of hash 这是因为问题部分是哈希数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.