Search code examples
ruby-on-railsmodelshas-many

Accessing model data with has_many relationship in Rails


I have the following models:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  attr_accessible  :name, :email, :password, :password_confirmation, :remember_me

  has_many :rulesets
end

class Ruleset < ActiveRecord::Base
  attr_accessible :title, :game_id, :user_id

  validates :game_id, presence: true
  validates :user_id, presence: true
  validates :title, presence: true

  belongs_to :user
  belongs_to :game
  has_many :rules
end

class Rule < ActiveRecord::Base
  attr_accessible :description, :ruleset_id
  belongs_to :ruleset

  validates :description, presence: true
  validates :ruleset_id, presence: true
end

I have a controller called PagesController that controls the user dashboard, where I want to display the number of rulesets and number of rules that a user has. this is my controller

class PagesController < ApplicationController

  def home
  end

  def dashboard
    @rulesets = current_user.rulesets 
  end
end

In my dashboard view, I'm attempting to display the rulesets and rules counts as such:

<% if current_user.rulesets.any? %>
  <li><%= @rulesets.count %> Ruleset</li>
  <li><%= @rulesets.rules.count%> Rules</li>
<% end %>

This returns the right number of rulesets if I just try and count the rulesets. When I try and count the rules, I get this and "undefined method `rules'" error. How am I supposed to access the rules that are in the users' ruleset?


Solution

  • You need to count all of the rulesets and the rules for each ruleset. Use something like:

    @rulesets.collect {|r| r.rules.count}.sum