Abdul Ahmad
Abdul Ahmad

Reputation: 10021

Rails add record with foreign key

I have a basic app that I'm testing on. I have 2 models:

Post
  id: int
  name:string
  content: string
  author_id: int <-- this is just a user_id, but I want to specify that it's an author
  belongs_to: :user

User
  id: int
  name: string
  has_many: :posts

I generated a basic scaffolding with controllers and views. The problem is, when I try to create a new post and I submit data to the controller, I get an error:

user must exist

When I create a post, I just pass a basic int id to the author_id field (I know I have ids 1-4), is the problem with the naming? Should posts have a FK named 'user_id' instead of 'author_id'?

what If I need multiple user ids for different fields?

for example, if posts can be reviewed, then each post would have many reviewers and each reviewer can review many posts. What would that go under? Wouldnt that be a user_id too?

Upvotes: 1

Views: 883

Answers (1)

Paweł Duda
Paweł Duda

Reputation: 1783

In your Post model, you need to specify custom foreign key like this:

class Post < ActiveRecord::Base
  belongs_to :user, foreign_key: :author_id
end

If you need one post to have many reviewers, you would probably need a join table for that - you can read more on this topic here, in Rails documentation: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Upvotes: 2

Related Questions