简体   繁体   English

Rails 4:通过关联循环

[英]Rails 4: Looping through association

I am having some trouble while looping some association: 循环某些关联时遇到一些麻烦:

#=> member.rb
has_one :academic

#=> academic.rb
belongs_to :member

So far so good. 到现在为止还挺好。 However, when I loop through the association, I get: 但是,当我遍历关联时,会得到:

undefined method 'each' for #<Academic:0x007fc98b2b7210>

Here's my view (show): 这是我的观点(显示):

<% if !@member.academic.nil? %>
 <% fields_academic = [:major, :second_major, :minor, :second_minor] %>

  <h1>Academics</h1>

  <% @member.academic.each do |academic| %>
 <%= render 'database/shared/display', model_obj: academic, data: academic, fields: fields_academic %>
  <% end %>
<% end %>

The code is stuck at the each method. 代码停留在each方法上。

@member is defined as = Member.find(params[:id]) @member定义为= Member.find(params[:id])

Any help will be gladly appreciated. 任何帮助将不胜感激。 Thank you in advance! 先感谢您!

According to your code there are no multiple instances of academic related to the given member (it's defined using has_one relation). 根据您的代码,不存在与给定member相关的academic多个实例(它是使用has_one关系定义的)。

The answer is: you cannot loop them. 答案是:您无法循环播放它们。

The correct code for your view should be: 您的视图的正确代码应为:

<% if @member.academic.present? %>
 <% fields_academic = [:major, :second_major, :minor, :second_minor] %>
  <h1>Academics</h1>
  <%= render 'database/shared/display', model_obj: @memeber.academic, data: academic, fields: fields_academic %>
 <% end %>
<% end %>

If your intention was to have many academics for a memeber, then use has_many instead. 如果您打算邀请许多学者参加,那么请使用has_many

class Member
  has_many :academics
end

each should be used on a collection of records ( I mean which results in a multiple records). each都应用于记录集合 (我的意思是这会导致多个记录)。 Currently @member.academic will return a single record as it is a has_one relation between member and academic , so you can't loop with that. 当前@member.academic将返回一条记录,因为这是memberacademic member之间的has_one关系,因此您无法循环访问。 May be you should change your association to has_many :academics and loop it like <% @member.academics.each do |academic| %> 可能是您应该将关联更改为has_many :academics并像<% @member.academics.each do |academic| %>循环它<% @member.academics.each do |academic| %> <% @member.academics.each do |academic| %>

Method :each iterates over the block according to how this Enumerable was constructed. 方法:每个方法根据此Enumerable的构造方式遍历该块。 If no block is given, returns self. 如果没有给出块,则返回self。 Enumerable is a mixin that provides to collections some useful methods. Enumerable是一个mixin,它为集合提供了一些有用的方法。 In your example academic is a not Enumerable, but single object. 在您的示例中, academic不是一个不可枚举的对象,而是一个单一的对象。 You should use has_many association. 您应该使用has_many关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM