Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing model data with has_many relationship in Rails
    text
    copied!<p>I have the following models:</p> <pre><code>class User &lt; 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 &lt; 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 &lt; ActiveRecord::Base attr_accessible :description, :ruleset_id belongs_to :ruleset validates :description, presence: true validates :ruleset_id, presence: true end </code></pre> <p>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</p> <pre><code>class PagesController &lt; ApplicationController def home end def dashboard @rulesets = current_user.rulesets end end </code></pre> <p>In my dashboard view, I'm attempting to display the rulesets and rules counts as such:</p> <pre><code>&lt;% if current_user.rulesets.any? %&gt; &lt;li&gt;&lt;%= @rulesets.count %&gt; Ruleset&lt;/li&gt; &lt;li&gt;&lt;%= @rulesets.rules.count%&gt; Rules&lt;/li&gt; &lt;% end %&gt; </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload