"rake db:migrate" 时不断出现语法错误

Keep getting syntax error when "rake db:migrate"

我的代码:

class Song < ActiveRecord::Base
   belongs_to :artist
   has_many :song_genres
   has_many :genres, :through :song_genres
end

错误:

rake aborted!
SyntaxError: .../app/models/song.rb:4: syntax error, unexpected ':', expecting keyword_end
has_many :genres, :through :song_genres

当我使用“=>”时:

class Song < ActiveRecord::Base
  belongs_to :artist
  has_many :song_genres
  has_many :genres, :through => :song_genres
end

我没有再收到错误消息,但现在我收到另一条错误消息,说明我在一次迁移中遇到类似情况。

rake aborted!
SyntaxError: .../db/migrate/01_create_artists_table.rb:4: syntax error, unexpected tSYMBEG, expecting keyword_end
                t.string :name

那里的代码如下所示:

class CreateArtistsTable < ActiveRecord::Migration
  def change
        create_table :artists |t|
        t.string :name
        t.has_many :songs 
        t.has_many :genres, through: :song_genres 
        end 
  end
end

我是新手,非常感谢您的帮助!谢谢! :)

create_table :artists |t| 应该是 create_table :artists do |t|

此外,以下两行不应在 artists 迁移中。他们错了。这不是在 Rails 中创建许多直通关系的方式。它们应该是模型的一部分,而不是迁移。

t.has_many :songs 
t.has_many :genres, through: :song_genres

Song模型里面,这样写。

has_many :genres, through: :song_genres

song_genres 创建迁移 table 喜欢建立有很多关系。

create_table :song_genres do |t|
  t.belongs_to :songs
  t.belongs_to :genres
end

为您的第一条错误消息尝试以下语法:

has_many :genres, through: :song_genres

这里有两个问题。在您的模型中,关键字参数的语法错误。在 ruby 中,您可以通过将冒号 放在关键字 之后和值之前来将参数作为关键字传递,例如 key: :value 而不是 :key :value。单词前的冒号声明一个符号,这不是您在这里所做的。所以,你的模型实际上应该是这样的:

class Song < ActiveRecord::Base
   belongs_to :artist
   has_many :song_genres
   # has_many :genres, :through :song_genres
   has_many :genres, through: :song_genres
   # Which is shorthand for `has_many :genres, :through => :song_genres`
end

而且,在您的迁移中,您不能指定 through。那是只存在于您的模型中的东西。您还弄错了迁移的语法。它应该看起来更像这样:

create_table :table_name do |t|
  t.type :column_name
end

当您说 t.has_many 时,您要求 ActiveRecord 创建类型为 "has_many" 的列,该类型不是有效类型。相反,您需要 stringintegerdatetime 等。要引用另一个 table,您可以 t.references。因此,您的迁移应该更像这样:

class CreateArtistsTable < ActiveRecord::Migration
  def change
        create_table :artists |t|
        t.string :name
        t.<type> :songs 
        t.<type> :genres #, through: :song_genres 
        end 
  end
end

具体来说,考虑到您要建立的关系,它会更像这样:

class CreateArtistsTable < ActiveRecord::Migration
  def change
    create_table :artists |t|
      t.string :name
    end 
    add_reference :songs, :artist
    create_table :song_genres do |t|
      t.references :song
      t.references :genre
    end
  end
end

附带说明,在 ruby 中,您应该使用 2 个空格进行缩进。