我不知道什么地方出了问题,但我无法得到belongs_to:class_name选项。有人可以启发我吗?非常感谢!belongs_to与:class_name选项失败
这是从我的代码片段。
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 的Rails 2.3.5
我在乎具有良好的外键。我不会应用关于重命名该列的建议,因为当列名称正确时,它更清楚发生了什么。 – 2010-04-21 19:33:28
无论哪种方式工作。无论对你和你的团队有意义,都是正确的做法。 :) – 2010-04-21 19:53:24
并认为class_name:'用户'将是足够的 – Donato 2015-03-30 21:25:57