EricLowber
EricLowber

Reputation: 133

Why am I getting syntax error, unexpected '}', expecting keyword_end with scope?

I'm a beginner, and have been learning Ruby on Rails for about 10 weeks now. When trying to run an RSpec test on one of my models, I get this error:

rb:4: syntax error, unexpected '}', expecting keyword_end

It looks like my brackets are closed and I have ended properly.

class Item < ActiveRecord::Base
  belongs_to :list

  scope :created_after, -> (7.days.ago) { where("item.created_at > ?", 7.days.ago) }

 end

The purpose of the scope is to be able to differentiate items that are older than 7 days from items written in the last week.

Here is my schema for this the list model:

  create_table "items", force: true do |t|
    t.string   "body"
    t.integer  "list_id"
    t.boolean  "done",       default: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end`

I've looked at the Rails Guides and have searched repeatedly but can't find anything that tells me my current syntax is wrong. Any ideas?

Upvotes: 1

Views: 1234

Answers (1)

Pete
Pete

Reputation: 2246

The issue is with how you have defined your lambda. As you just started learning Ruby & Rails I would recommend you read this article to understand what lambdas are, how they operate and what the syntax is. The code in round brackets should be a variable name that can be passed into the lambda rather than a definition of a date. E.g your code:

scope :created_after, -> (7.days.ago) { where("item.created_at > ?", 7.days.ago) }

Should be:

scope :created_after, -> (date) { where("item.created_at > ?", date) }

That way you can create queries on Items like this:

new_items = Item.created_after(7.days.ago) # or..
newer_items = Item.created_after(3.days.ago) # or...
new_done_items = Item.where(done: true).created_after(7.days.ago) # etc

Upvotes: 3

Related Questions