Home > OS >  Rails belongs_to or has_one association with custom name
Rails belongs_to or has_one association with custom name

Time:11-20

I am trying to create association between active record objects with custom name.

For example, I have a User table and Post class, and Post class has writer_id and reader_id. I want to create association for both writer_id and reader_id so that I can just call post.writer to get the User object. I have tried multiple options (one of them: Rails belongs_to with custom column name), but it did not solve the problem. Anyone knows how to unblock this issue?

CodePudding user response:

try this

class Post < ApplicationRecord
  belongs_to :writer, class_name: 'User'
  belongs_to :reader, class_name: 'User'
end

sorry, initially I put class instead of class_name

CodePudding user response:

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.

  • Related