In this case you should be using belongs_to
since the foreign key should be stored on the posts table:
class Post < ApplicationRecord
belongs_to :author,
class_name: 'User'
end
class CreatePosts < ActiveRecord::Migration[7.0]
def change
create_table :posts do |t|
t.references :author,
null: false,
foreign_key: { to_table: :users }
t.timestamps
end
end
end
class User < ApplicationRecord
has_many :posts_as_author,
class_name: 'Post',
foreign_key: :author_id
end
This creates a one to many assocation. Note that the foreign_key
option is required in the has_many
assocation since its normally derived from the name of the class.
has_one
wouldn't work since it means that you would be storing a post_id
on the users
table. has_one
always has a corresponding belongs_to
on the other side of the assocation. has_one
is basically just has_many
with a LIMIT 1
tacked onto the query and generates slighly different methods.
When it comes to readers I can almost guarentee what you actually want is a many to many assocation.