我正在尝试建立以下关联。
class Task < ApplicationRecord
belongs_to :user
has_one :organziation, through: :user
end
class User < ApplicationRecord
belongs_to :organization
has_many :tasks
accepts_nested_attributes_for :organization
end
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
我希望能够从任务中获取任务组织的目录。
答案 0 :(得分:2)
您的关联名称中有拼写错误。纠正它:
has_one :organization, through: :user
您有 organziation ,我将其更改为 organization 。
答案 1 :(得分:1)
我认为您应该将has_many :tasks
添加到组织模型
因为您看到,如果组织被销毁,如果您在此处使用dependent: :destroy
,那么与该组织相关的所有任务也应该被销毁,也可以获得与该组织相关的所有任务,您可能需要它