1

I have a migration file create_subject (code of which is below), a Subject class contains scopes using lambda syntax. When I call Subject.visible, I get syntax errors.

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

      t.timestamps
    end
  end

  def down
    drop_table :subjects
  end
end

This is my Subject class

Console error log

irb(main):003:0> Subject.visible
SyntaxError: C:/Users/SS/Sites/simple_cms/app/models/subject.rb:3: syntax error, unexpected =>, expecting ')'
scope :visible, -> { where (:visible => true) }
                                   ^
C:/Users/SS/Sites/simple_cms/app/models/subject.rb:4: syntax error, unexpected =>, expecting ')'
scope :invisible, -> { where (:visible => false) }
                                     ^
C:/Users/SS/Sites/simple_cms/app/models/subject.rb:7: syntax error, unexpected '|'
scope :search, -> {|query| where (["name LIKE ?", "%#{query}%"]) }
                ^
C:/Users/SS/Sites/simple_cms/app/models/subject.rb:7: syntax error, unexpected ( arg, expecting keyword_do or '{' or '('
scope :search, -> {|query| where (["name LIKE ?", "%#{query}%"]) }

2 Answers 2

4

Do not put space before opening parenthesis when calling methods. It should be like this

class Subject < ApplicationRecord
  scope :visible, -> { where(:visible => true) }
  scope :invisible, -> { where(:visible => false) }
  scope :sorted, -> { order("position ASC") }
  scope :search, ->(query) { where(["name LIKE ?", "%#{query}%"]) }
  # and so on ...
end
Sign up to request clarification or add additional context in comments.

3 Comments

(THANK YOU, for replying. Looks like most of the errors are fixed. BUT): irb(main):001:0> Subject.visible SyntaxError: C:/Users/SS/Sites/simple_cms/app/models/subject.rb:7: syntax error, unexpected '|' scope :search, -> {|query| where(["name LIKE ?", "%#{query}%"]) }
I literally cant be more thankful to you sir @Michal. I felt like i've lost learning this language. Thank you so so very much...
@SafiUllah You can accept the answer if it solved your problem
1

If you are going to put query in pipes |query| then use:

scope :search,lambda{|query| where(["name LIKE ?", "%#{query}%"]) }

instead of

scope :search, ->(query) { where(["name LIKE ?", "%#{query}%"]) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.