【问题标题】:Reference a single column from one table 2 times to another table将一个表中的单个列引用到另一个表 2 次
【发布时间】:2015-06-07 06:54:52
【问题描述】:

我有两张桌子:

  1. 用户
  2. 帖子

一个帖子属于一个用户,一个帖子可以授予另一个用户。如何在 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

我该如何解决这个问题?

【问题讨论】:

  • 请看any of these是否有帮助。如果他们这样做了,请点击“关闭”告诉系统这个问题与有帮助的问题重复。
  • @WayneConrad 不,他们没有帮助。它们都使用分配的:class_name 中的相同:class_name:foreign_key。我想要的是:class_name 应该是相同的,但:foreign_key 不应该来自分配的:class_name,而是来自posts 模型。
  • 从概念上讲,外键awarded_to_user_id必须在users表中,因为belongs_to是用户,而has_one是一个帖子。对于您所说的,您必须还原场景:Post belongs_to :awarded_userUser has_one :awarded_post
  • @ArslanAli 你能用代码发布答案吗?作为一个初学者,理解这一点真的很复杂。 :)

标签: ruby-on-rails ruby foreign-keys associations


【解决方案1】:

首先,生成一个将列添加到帖子表中的迁移。

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

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 1970-01-01
    • 2010-10-20
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多