我的代码:
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
我是新手,所以我非常感谢您的帮助!谢谢!:)
你这里有两个问题。在您的模型中,关键字参数的语法是错误的。在 ruby 中,您可以通过在关键字之后和值之前放置冒号来将参数作为关键字传递,就像 sokey: :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”的列,该列不是有效类型。相反,您需要类似string
、integer
、datetime
等的内容。要引用另一个表,您可以执行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 个空格进行缩进。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句