2010-04-21 24 views
19

Neyin yanlış gittiğine dair hiçbir fikrim yok ama belongs_a ile çalışamıyorum: class_name option. Birisi beni aydınlatır. Çok teşekkürler!belongs_to ile: class_name seçeneği başarısız oldu

İşte kodumdan bir parça.

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 

ortamı: yabancı anahtar yazar kimliği ise

yakut 1.9.1-P387 Raylar 2.3.5

cevap

6

O

belongs_to :user, :foreign_key => 'author_id' 

olmalıdır. Kullanıcı sınıfına sahip olduğunuzdan, Kitabınızın ait_to: kullanıcısı olmalıdır. yapmak

52
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 

en iyi şey göçü değiştirip user_id için author_id değiştirmektir. Daha sonra :foreign_key seçeneğini kaldırabilirsiniz.

+6

. Sütunun doğru ismine sahip olduğunda neler olup bittiği daha net olduğu için, sütunu yeniden adlandırmayla ilgili öneriyi uygulamam. –

+1

Her iki durumda da çalışıyor. Siz ve ekibiniz için mantıklı olan şey, yapılacak en doğru şey. :) –

+2

Ve class_name düşünmek için: 'Kullanıcı' yeterli olurdu – Donato

0

ben bu şekilde yapın:

Göç -

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

sınıf Yayınla İyi yabancı anahtarları olan umurumda

belongs_to :author, class_name: "User"