views:

80

answers:

2

Just starting to use Ruby on Rails to see what its like.

I have a user model with an id and a post model with an adderId. The adderId of the post model should be the user id of the user that created it.

How can I relate these with Ruby on Rails?

+1  A: 

It looks like this question seems to be doing what you're trying to do.

Sorry if I misunderstood your question, I too am new to Ruby on Rails.

Jorge Israel Peña
+4  A: 

The Rails convention for foreign keys would give your Post model a user_id column rather than adderId. You can break the convention, but that requires slightly more configuration, as below:

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => :adderId
end

class Post < ActiveRecord::Base
  belongs_to :adder, :class_name => "User", :foreign_key => :adderId
end

If you gave Post a user_id instead, you could do this:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

I'd recommend taking a look at the Rails Guide for Active Record Associations, which covers all of the above and plenty more.

Greg Campbell