Taylor Huston
Taylor Huston

Reputation: 1140

Rails, issue selecting by boolean

I'm working through a Rails tutorial, and have hit a wall I'm not sure if I missed a step. I have two models, both with a boolean called 'visible', but I can only select using it on one of the models. For reference here are my migrations

class CreateSubjects < ActiveRecord::Migration
  def up
    create_table :subjects do |t|
      t.string "name"
      t.integer "position"
      t.boolean "visible", :default => false

      t.timestamps null: false
    end
  end

  def down
    drop_table :subjects
  end

end

And

class CreatePages < ActiveRecord::Migration
  def up
    create_table :pages do |t|
      t.integer "subject_id"
      t.string "name"
      t.string "permalink"
      t.integer "position"
      t.boolean "visible", :default => false

      t.timestamps null: false
    end
    add_index("pages", "subject_id")
    add_index("pages", "permalink")
  end

  def down
    drop_table :pages
  end

end

Both have a t.boolean "visible", :default => false in them. And I can edit them and change that value fine. But if I say pull up a rails console and try...

This works fine:

Subject.visible

This gives me a NoMethodError: undefined method `visible':

Page.visible

During one point in the tutorial I had to change the line

@page.sections.visible.sorted.each

to

@page.sections.where(:visible => true).sorted.each

Which did work, but I have no idea WHY I had to do so

Link to project on GitHub if it helps https://github.com/TaylorHuston/Rails_LyndaCMS

Upvotes: 2

Views: 54

Answers (1)

Shalev Shalit
Shalev Shalit

Reputation: 1963

The visible function is an instance function, so you have to use it on an instance of Page:

Page.new.visible

You were able to use it on Subject because you created a scope :visible, so you have one function for the instance and one for the Relation.

Upvotes: 3

Related Questions