has_many虽然关系不起作用

时间:2016-08-05 20:31:52

标签: ruby-on-rails

我正在尝试建立以下关联。

task.rb

class Task < ApplicationRecord
    belongs_to :user
    has_one :organziation, through: :user
end

user.rb

class User < ApplicationRecord
    belongs_to :organization
    has_many :tasks
  accepts_nested_attributes_for :organization
end

organization.rb

class Organization < ApplicationRecord
    has_many :users
end

这是我的控制台输出:

2.3.0 :001 > t = Task.last
  Task Load (0.2ms)  SELECT  "tasks".* FROM "tasks" ORDER BY "tasks"."id" DESC LIMIT ?  [["LIMIT", 1]]
 => #<Task id: 3, name: "Register Students", created_at: "2016-08-05 20:00:34", updated_at: "2016-08-05 20:00:34", user_id: 5>
2.3.0 :002 > t.user
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]
 => #<User id: 5, email: "rich@wintas.com", created_at: "2016-08-05 19:59:56", updated_at: "2016-08-05 20:00:07", organization_id: 1, admin: false>
2.3.0 :003 > t.organization
NoMethodError: undefined method `organization' for #<Task:0x007fbf8bc6d1

我希望能够从任务中获取任务组织的目录。

2 个答案:

答案 0 :(得分:2)

您的关联名称中有拼写错误。纠正它:

has_one :organization, through: :user

您有 organziation ,我将其更改为 organization

答案 1 :(得分:1)

我认为您应该将has_many :tasks添加到组织模型

因为您看到,如果组织被销毁,如果您在此处使用dependent: :destroy,那么与该组织相关的所有任务也应该被销毁,也可以获得与该组织相关的所有任务,您可能需要它