【问题标题】:belongs_to with :class_name option fails带有 :class_name 选项的 belongs_to 失败
【发布时间】:2010-04-21 16:45:05
【问题描述】:

我不知道出了什么问题,但我无法使用 :class_name 选项让 belongs_to 工作。有人可以启发我。非常感谢!

这是我的代码片段。

class CreateUsers < ActiveRecord::Migration
    def self.up
        create_table :users do |t|
            t.text :name
        end
    end

    def self.down
        drop_table :users
    end
end

#####################################################

class CreateBooks < ActiveRecord::Migration
    def self.up
        create_table :books do |t|
            t.text :title
            t.integer :author_id, :null => false
        end
    end

    def self.down
        drop_table :books
    end
end

#####################################################

class User < ActiveRecord::Base
    has_many: books
end

#####################################################

class Book < ActiveRecord::Base
    belongs_to :author, :class_name => 'User', :validate => true
end

#####################################################

class BooksController < ApplicationController
    def create
        user = User.new({:name => 'John Woo'})
        user.save
        @failed_book = Book.new({:title => 'Failed!', :author => @user})
        @failed_book.save # missing author_id
        @success_book = Book.new({:title => 'Nice day', :author_id => @user.id})
        @success_book.save # no error!
    end
end

环境:

红宝石 1.9.1-p387 导轨 2.3.5

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:
    class User < ActiveRecord::Base
      has_many :books, :foreign_key => 'author_id'
    end
    
    class Book < ActiveRecord::Base
      belongs_to :author, :class_name => 'User', :foreign_key => 'author_id', :validate => true
    end
    

    最好的办法是更改您的迁移并将author_id 更改为user_id。然后您可以删除:foreign_key 选项。

    【讨论】:

    • 我关心拥有好的外键。我不会应用有关重命名列的建议,因为当列具有正确的名称时会更清楚发生了什么。
    • 任何一种方式都可以。任何对您和您的团队有意义的事情都是正确的。 :)
    • 并且认为 class_name: 'User' 就足够了
    【解决方案2】:

    应该是

    belongs_to :user, :foreign_key => 'author_id'
    

    如果您的外键是作者 ID。由于您实际上有 User 类,因此您的 Book 必须属于_to :user。

    【讨论】:

      【解决方案3】:

      我是这样做的:

      迁移-

      class AddAuthorToPosts < ActiveRecord::Migration
        def change
          add_reference :posts, :author, index: true
          add_foreign_key :posts, :users, column: :author_id
        end
      end
      

      类帖

        belongs_to :author, class_name: "User"
      

      【讨论】:

        【解决方案4】:

        迁移

        t.belongs_to :author, foreign_key: { to_table: :users }
        

        在 Rails 5 上工作

        【讨论】:

          猜你喜欢
          • 2011-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-03
          • 1970-01-01
          相关资源
          最近更新 更多