无法确定“模型A是属于模型B”还是“模型B属于模型A”?

时间:2012-05-26 23:33:57

标签: ruby-on-rails associations

考虑两个模型:

  1. User => (id:integer,name:string,created_at:datetime,updated_at:datetime,department_id:integer)
  2. Department => (id:integer,name:string,created_at:datetime,updated_at:datetime)
  3. 现在,这两个表之间存在明显的关系。它是

    • 每个User都有一个部门
    • Department属于许多用户,即单个部门中有多个用户

    所以,我选择epress和A belongs_to B

    一样
    class User < ActiveRecord::Base
      has_one :department
    end
    class Department < ActiveRecord::Base
      belongs_to :user
    end
    

    但是你可能知道不起作用&amp;抛出以下错误:

    > @user = User.find(1)
    > @user.department.name
      Department Load (1.0ms)  SELECT "departments".* FROM "departments" WHERE "departments"."user_id" = 1 LIMIT 1
    ActiveRecord::StatementInvalid: PG::Error: ERROR:  column departments.user_id does not exist
    

    经过大量的热播&amp;审判。我偶然发现了正确的方法来定义这个,这是另一种方式,即B belongs to A

    class Department < ActiveRecord::Base
      has_many :users
    end
    class User < ActiveRecord::Base
      belongs_to :department
    end
    > @user = User.find(1)
    > @user.department.name
    Department Load (1.0ms)  SELECT "departments".* FROM "departments" WHERE "departments"."id" = 1 LIMIT 1
     => "HR"
    

    现在,这与我的大脑对这些关联的思考方式完全相反。所以,我有点困惑,所以如果有人能解释发生了什么?

    为什么B belongs to A&amp;不是A belongs to B

3 个答案:

答案 0 :(得分:2)

你的模特错了。它们应该是这样的:

class User < ActiveRecord::Base
  belongs_to :department
end

class Department < ActiveRecord::Base
  has_many :users
end

因此,要向用户添加部门,您可以执行以下操作:

@user.department.create(:name => 'Science Department')

要将用户添加到部门,您可以执行以下操作:

@department.users.create(:name => 'John')

答案 1 :(得分:1)

第一眼看:has_one关系有点奇怪。考虑一个用户和一个帐户,每个帐户只与一个用户连接(属于),另一方面是用户has_one帐户,只有一个帐户。帐户是用户拥有的东西。

在这些情况下,您使用has_one模型上的User关系,Rails将在user_id表格中搜索accounts列(请参阅has_one documentation在Rails指南中。)

在您的具体案例中,我认为完全正确的说“部门有很多用户”和“用户属于部门”。

答案 2 :(得分:-1)

在第一个示例中,您需要添加列&amp;迁移文件中表的索引

class AddRelationToDeparments < ActiveRecord::Migration
  def change
    add_column, :deparments, :user_id, :integer
    add_index, :deparments: :user_id
  end
end
相关问题