我有嵌套关系,并根据Rails Guide建立了它们。
User
有许多Collections
,其中有许多Sections
,每个都包含许多Links
。但是,在创建新的Link
时,user_id
未被分配,但始终为nil
。 section_id
和collection_id
的设置正确。
class Api::V1::LinksController < Api::V1::BaseController
acts_as_token_authentication_handler_for User, only: [:create]
def create
@link = Link.new(link_params)
@link.user_id = current_user
authorize @link
if @link.save
render :show, status: :created
else
render_error
end
end
private
def link_params
params.require(:resource).permit(:title, :description, :category, :image, :type, :url, :collection_id, :user_id, :section_id)
end
def render_error
render json: { errors: @resource.errors.full_messages },
status: :unprocessable_entity
end
end
用户
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 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 Link < ApplicationRecord
belongs_to :section
end
这是建立关系的正确方法,有人可以帮助我了解我所缺少的吗?
答案 0 :(得分:2)
你不能做
@link.user_id = current_user
您可以(代替)做...
@link.user_id = current_user.id
或更优雅...
@link.user = current_user
假设您将在模型中定义关系
class Link < ApplicationRecord
belongs_to :section
belongs_to :user
end
但是正如Andrew Schwartz在评论中指出的那样,将字段user_id
添加到links
表中可能是设计错误。在User
模型has_many :links, through: :sections, dependent: :destroy
中,您没有使用链接记录中的任何user_id字段。它使用user_id
表
collections
字段
仅将user_id
添加到links
表中并不意味着当您执行my_user.links
时链接将被返回……不会。
由于您在section_id
中传递了一个link_params
,足以创建到用户的链接,因此只需编写迁移操作以删除user_id
字段即可。如果您希望能够从链接中看到关联的用户,请执行...
class Link < ApplicationRecord
belongs_to :section
has_one :collection, through: :section
has_one :user, through: :collection
end
,这将使您执行my_link.user
来检索链接的用户。