简体   繁体   English

Rails belongs_to 或 has_one 与自定义名称的关联

[英]Rails belongs_to or has_one association with custom name

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 .例如,我有一个User表和Post class,而Post class 有writer_idreader_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.我想为writer_idreader_id创建关联,这样我就可以调用post.writer来获取User object。我尝试了多种选择(其中之一: Rails belongs_to with custom column name ),但它没有解决问题. Anyone knows how to unblock this issue?任何人都知道如何解锁这个问题?

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抱歉,最初我输入class而不是class_name

In this case you should be using belongs_to since the foreign key should be stored on the posts table:在这种情况下,你应该使用belongs_to因为外键应该存储在 posts 表中:

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_many关联中需要foreign_key选项,因为它通常派生自 class 的名称。

has_one wouldn't work since it means that you would be storing a post_id on the users table. has_one不起作用,因为这意味着您将在users表上存储一个post_id has_one always has a corresponding belongs_to on the other side of the assocation. has_one在关联的另一端总是有一个相应的belongs_to has_one is basically just has_many with a LIMIT 1 tacked onto the query and generates slighly different methods. has_one基本上只是has_many加上一个LIMIT 1到查询并生成略有不同的方法。

When it comes to readers I can almost guarentee what you actually want is a many to many assocation.对于读者,我几乎可以保证您真正想要的是多对多关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM