将一个表中的单个列引用到另一个表

时间:2015-06-06 22:04:35

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

我有两张桌子:

  1. 用户
  2. 帖子
  3. 帖子属于用户,帖子可以授予其他用户。如何在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

    我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先,生成一个将列添加到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