Rails ActiveRecord_Relation

时间:2014-12-25 13:21:49

标签: ruby-on-rails ruby ruby-on-rails-3

我目前正在开发一个有点'大'的项目。在这个项目中,我有许多模型,视图和控制器,我必须提到以下内容: Group.rb:

class Group < ActiveRecord::Base
    has_many :users, through: :grouprel
    has_many :grouprel, dependent: :destroy
    validates :name, presence: true, length: {maximum: 25},
                              uniqueness: { case_sensitive: false }
    validates :description, presence: true , length: {maximum: 140}
end

Grouprel.rb

class Grouprel < ActiveRecord::Base
    belongs_to :user
    belongs_to :group
    validates :user_id, presence: true
    validates :group_id, presence: true
end

User.rb

class User < ActiveRecord::Base
.....
  has_many :groups, through: :grouprel, dependent: :destroy
  has_many :grouprel, dependent: :destroy
.....

StaticPageController:

class StaticPagesController < ApplicationController
  def home
    if logged_in?
      @tweet = current_user.tweets.build
      @feed_items = current_user.feed.paginate(page: params[:page])
      @groupi = Grouprel.where(user_id: current_user.id).pluck(:group_id)
      @groupies = Group.where(id: @groupi).paginate(page: params[:page])
    end
  end
.....

end

Home.html.erb:

<% if logged_in? %>
.......
      <section class="user_info">
        <%= render 'shared/group_participation' %>
      </section>
    </aside>
 .............

_group_participation.html.erb

<h5> Your groups: </h5>
<% if @groupies %>
<ol class="tweets">
    <%= content_tag_for(:li, @groupies) do %>
      <%= link_to @groupies.name, group_path(@groupies) %>
    <% end %>
</ol>
 <%= will_paginate @groupies %>
<% end %>  

这里我想显示用户所属的每个组。尝试在StaticPagesController中获取@groupies时出现的错误是%23<Group::ActiveRecord_Relation:0x007f86b00f6ed0>。我检查了我的rails控制台,它应该返回一些东西。

我对rails和ruby的有限知识可以说明这是一个问题,因为StaticPageController无法看到Grouprel.rb表。我试图将控制器包含在herlpers中。我甚至尝试定义一个方法,在应用程序控制器中返回'groupies',然后在StaticPagesController中使用它。我可以得到一个提示我为什么会返回错误的提示吗?

如果我的帖子必须包含更多规格,请告诉我将在第二次看到请求时将其发布

1 个答案:

答案 0 :(得分:1)

您不是在groupies集合上进行迭代,而是在集合本身上调用name方法。 content_tag_for 可以为您迭代集合,但您需要使用它为块生成的值:

<%= content_tag_for(:li, @groupies) do |group| %>
  <%= link_to group.name, group_path(group) %>
<% end %>