ruby on rails -将一个表中的单个列引用到另一个表2次



我有两个表:

    用户
  1. 文章

一个帖子属于一个用户,一个帖子可以授予另一个用户。我如何在rails模型中映射这种关联?

这些是我当前的关联,它们不起作用:

class Post < ActiveRecord::Base
    belongs_to :user
    has_one :awarded_user, :class_name => 'User', :foreign_key => 'awarded_to_user_id'

当我尝试访问post.awarded_user时,我在rails控制台得到这个错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.awarded_to_user_id' in 'where clause': SELECT  `users`.* FROM `users` WHERE `users`.`awarded_to_user_id` = 8 LIMIT 1

查询搜索user.awarded_to_user_id,然而,我需要它搜索posts以成为posts.awarded_to_user_id

如何解决这个问题?

首先,生成一个迁移,向posts表中添加一个列。

class AddAwardedToUserIdToPosts < ActiveRecord::Migration                   
  def change                                                                
    add_column :posts, :awarded_to_user_id, :integer, index: true
  end                                                                      
end

现在,在你的模型中:

class User < ActiveRecord::Base                                             
  has_many :posts                                
  has_one :awarded_post, class_name: 'Post', foreign_key: 'awarded_to_user_id'  
end

对于Post

class Post < ActiveRecord::Base                                             
  belongs_to :awarded_user, class_name: 'User', foreign_key: 'awarded_to_user_id'
  belongs_to :user
end

现在,在这种情况下,你可以实现你所说的:

user_zaid = User.create first_name: "Zaid"
user_ali = User.create first_name: "Ali"
post = Post.create description: "A less descriptive post"
post.user = user_zaid
post.awarded_user = user_ali
post.save

# Or the other way
user_ali.posts << post # Since, user has_many posts.
user_ali.awarded_post = post # Since, user has_one awarded_post. 
user_ali.save
# How to fetch:
User.last.posts # it will give you the posts.
User.last.awarded_post # it will give you the (single) awarded post. 

对于Post

Post.last.user # it will give you the user which it belongs to
Post.last.awarded_user # it will give you the user which it was **awarded** to

最新更新