1

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?

irl_irl
  • 3,785
  • 9
  • 49
  • 60

2 Answers2

5

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
  • 15,182
  • 3
  • 44
  • 45
1

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.

Community
  • 1
  • 1
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123