Search code examples
ruby-on-railsdevise

Rails: Unexpected tSYMBEG error from "has_many"


I use Windows10+Ubuntu18.04

I set "has_many" in a model, but an error message appears when I start the rails console:

/home/keaton/.rvm/rubies/ruby-2.6.6/bin/ruby: warning: shebang line ending with \r may cause problems
/home/keaton/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': /mnt/c/projects/Kasuri/app/models/user.rb:8: syntax error, unexpected tSYMBEG, expecting do or '{' or '('
  has_many :spaces, through: :space_users
           ^ (SyntaxError)

But I am sure I have no spelling mistakes, the source code of the rb file is as follows:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         #:recoverable, :rememberable, :validatable

  has_many :space_users, dependent: :destroy
  has_many :spaces, through: :space_users
  has_many :channel_users, dependent: :destroy
    has_many :channels, through: :channel_users
  has_many :messages, dependent: :destroy
end

I am using Devise to make the login function. Is this the reason for the exception? Thank you!


Solution

  • You have a trailing comma which was leftover when the next line was commented out:

    devise :database_authenticatable, :registerable,
    

    This causes the next expression has_many :space_users, dependent: :destroy to be treated as you're passing it as an argument to the devise method. So what the parser actually sees is:

    devise :database_authenticatable, :registerable, has_many :space_users, dependent: :destroy
    

    Parens are not optional in nested method calls:

    foo :a, bar :b
    # (irb):34: syntax error, unexpected symbol literal, expecting `do' or '{' or '(' (SyntaxError)   
    
    # works
    foo :a, bar(:b)