Ruby on rails 活动记录:未在嵌套关系中分配用户\u id

Ruby on rails 活动记录:未在嵌套关系中分配用户\u id,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我有嵌套的关系,并根据。 一个用户有许多集合,其中有许多部分,每个部分都包含许多链接。但是,在创建新的链接时,用户id不会被分配,而是始终为nil。正在正确设置部分\u id和集合\u id 控制器 class Api::V1::LinksController

我有嵌套的关系,并根据。 一个
用户
有许多
集合
,其中有许多
部分
,每个部分都包含许多
链接
。但是,在创建新的
链接时,
用户id
不会被分配,而是始终为
nil
。正在正确设置
部分\u id
集合\u id

控制器
class Api::V1::LinksController
模型 用户

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  acts_as_token_authenticatable
  has_many :collections, dependent: :destroy
  has_many :sections, through: :collections, dependent: :destroy
  has_many :links, through: :sections, dependent: :destroy

  mount_uploader :image, PhotoUploader
end
class用户
收藏

class Collection < ApplicationRecord
  belongs_to :user
  has_many :sections, dependent: :destroy
  has_many :links, through: :sections, dependent: :destroy

  mount_uploader :image, PhotoUploader
end
class Section < ApplicationRecord
  belongs_to :collection
  has_many :links, dependent: :destroy
end
类集合
部分

class Collection < ApplicationRecord
  belongs_to :user
  has_many :sections, dependent: :destroy
  has_many :links, through: :sections, dependent: :destroy

  mount_uploader :image, PhotoUploader
end
class Section < ApplicationRecord
  belongs_to :collection
  has_many :links, dependent: :destroy
end
class部分
链接

class Link < ApplicationRecord
  belongs_to :section
end
class链接
这是建立关系的正确方法吗?有人能帮我理解我缺少什么吗?

你不能这么做

@link.user_id = current_user
你可以(代替)做

或者更优雅地说

@link.user = current_user
假设您将在模型中定义关系

class Link < ApplicationRecord
  belongs_to :section
  belongs_to :user
end
这将允许您执行
my_link.user
来检索链接的用户。

您不能这样做

@link.user_id = current_user
你可以(代替)做

或者更优雅地说

@link.user = current_user
假设您将在模型中定义关系

class Link < ApplicationRecord
  belongs_to :section
  belongs_to :user
end

这将允许您执行
my_link.user
来检索链接的用户。

太好了,谢谢
@link.user\u id=当前用户.id
有效。但是,第二个解决方案
@link.user=current_user
不起作用,返回错误
“undefined method user=”for#后者不起作用,因为您尚未在
链接上定义
用户
关联。您可以通过设置必要的
has-many:through
关联:
节。has-one:user,through::coCollection
链接来完成此操作。has-one:user,through::Section
。但这是来自
Link#user_id
的独立信息源,因此我不会同时使用这两种方法。正如
link.user\u id
可能与
link.section.collection.user\u id
不同步,这也是您可能更喜欢通过关联而不是列的原因之一。@AndrewSchwartz说得很好。我会编辑我的答案,但如果你想发布答案,我肯定会投票。太好了,谢谢
@link.user\u id=当前用户.id
有效。但是,第二个解决方案
@link.user=current_user
不起作用,返回错误
“undefined method user=”for#后者不起作用,因为您尚未在
链接上定义
用户
关联。您可以通过设置必要的
has-many:through
关联:
节。has-one:user,through::coCollection
链接来完成此操作。has-one:user,through::Section
。但这是来自
Link#user_id
的独立信息源,因此我不会同时使用这两种方法。正如
link.user\u id
可能与
link.section.collection.user\u id
不同步,这也是您可能更喜欢通过关联而不是列的原因之一。@AndrewSchwartz说得很好。我会编辑我的答案,但如果你想发布答案,我肯定会投赞成票。