Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

belongs_to with :class_name option fails

I have no idea what went wrong but I can't get belongs_to work with :class_name option. Could somebody enlighten me. Thanks a lot!

Here is a snip from my code.

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 

environment:

ruby 1.9.1-p387 Rails 2.3.5

like image 455
crackpot Avatar asked Apr 21 '10 16:04

crackpot


People also ask

How would you choose between Belongs_to and Has_one?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

How associations work Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.


2 Answers

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 

The best thing to do is to change your migration and change author_id to user_id. Then you can remove the :foreign_key option.

like image 87
Tony Fontenot Avatar answered Sep 28 '22 00:09

Tony Fontenot


It should be

belongs_to :user, :foreign_key => 'author_id' 

if your foreign key is author id. Since you actually have User class, your Book must belong_to :user.

like image 25
Evgeny Shadchnev Avatar answered Sep 28 '22 01:09

Evgeny Shadchnev