gpt4 book ai didi

ruby-on-rails - 属于 :class_name option fails

转载 作者:行者123 更新时间:2023-12-03 10:08:14 25 4
gpt4 key购买 nike

我不知道出了什么问题,但我无法使用 :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

环境:

ruby 1.9.1-p387
rails 2.3.5

最佳答案

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_iduser_id .然后你可以删除 :foreign_key选项。

关于ruby-on-rails - 属于 :class_name option fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com