Martin Lang
Martin Lang

Reputation: 831

Has-Many and Belongs-to-one Relation

I'm trying to keep track of how many signup_conversions a user creates.
Therefore, I have those two following models:

signup_conversion.rb

class SignupConversion < ActiveRecord::Base
  belongs_to :user
  belongs_to :convertee, :class_name => "User", :foreign_key => 'convertee_id'
  attr_accessible :convertee_id
end

user.rb

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  belongs_to :signup_conversion
  has_many :signup_conversions
end

Would this work that way? Or am I missing something crucial here?

Upvotes: 2

Views: 2679

Answers (2)

deivid
deivid

Reputation: 5258

I haven't tried the code, but I give you some tips that hope you find useful.

  • I think every has_many/has_one statement should have its correspondent belongs_to, so three belongs_to and one has_many doesn't look good.

  • I'm not sure has_one :signup_conversion and has_many :signup_conversions would play well together, so I'd rather change the names. I changed the other names as well to try to make the associations clearer although I'm not sure I fully understand the real concepts they represent. You will probably come up with better names.

  • By default, the foreign key is guessed adding the suffix _id to the association name, so you don't need to specify it in this case. Also, I don't think you need to make that attribute accessible, at least not for the association to work.

    signup_conversion.rb

    class SignupConversion < ActiveRecord::Base
      belongs_to :owner    , :class_name => "User"
      belongs_to :convertee, :class_name => "User"
    end
    

    user.rb

    class User < ActiveRecord::Base
      attr_accessible :name, :email, :password, :password_confirmation
      has_one  :owned_signup_conversion     , :class_name => "SignupConversion"
      has_many :triggered_signup_conversions, :class_name => "SignupConversion"
    end
    

Upvotes: 3

anotherthink
anotherthink

Reputation: 491

You have more code than you need here; you only need

class SignupConversion < ActiveRecord::Base
   belongs_to :user
end

class User < ActiveRecord::Base
   attr_accessible :name, :email, :password, :password_confirmation
   has_many :signup_conversions
end

Then you need a user_id column in your signup_conversions table, and you call

@user.signup_conversions

in your views or controller.

Upvotes: 0

Related Questions