【问题标题】:Migration error when adding a column to an existing table将列添加到现有表时出现迁移错误
【发布时间】:2016-02-17 02:13:55
【问题描述】:

我正在尝试将用户用户名添加到 song

app/models/user.rb

class User < ActiveRecord::Base
  has_many :songs 
  ...
end

app/models/song.rb

class Song < ActiveRecord::Base
  belongs_to :user
  ...
end

我正在尝试进行迁移以将用户名表添加到我的歌曲表中

class AddUsernameToSongs < ActiveRecord::Migration
  def change
    add_column :songs, :username, :string
  end
end

但是当我尝试运行 rake db:migrate 时,我不断收到未初始化的常量错误

我希望能够对每首歌进行通话

<%= song.username %> 

发布曲目的作者。

我正在使用 devise 设置我的用户,并且 devise 表已经有一个用户名字段。

【问题讨论】:

  • 发布您的完整迁移错误和迁移的文件名。最后,song.username 并不神奇。您需要确保为该属性分配了一个值。
  • 您在 song.rb 中的 belongs_to :user 行将假设您在歌曲表中有一个 user_id 列。你有这个外键列吗?
  • 不要在歌曲表中添加用户名列。如果您正确设置了关系,您应该可以通过 song.user.username 访问用户名

标签: ruby-on-rails devise


【解决方案1】:

最好通过 id 将歌曲链接到用户,而不仅仅是用户名。

如果你还没有这个。我认为你做你说你有一个协会。

class AddUserToSongs < ActiveRecord::Migration
  def change
    add_column :songs, :user_id, :integer
  end
end

在您的歌曲模型中,您可以添加一个名为 ** author ** 的方法

class Song < ActiveRecord::Base
  belongs_to :user
  ...
  def author
    user.name # this can be username or what ever field in the user's table you want 
  end
end

现在在你看来,你可以做这样的事情。

- songs.each do |song|
  = song.author
  %br

我希望这会有所帮助。 快乐黑客

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2018-11-01
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多