我有嵌套关系,并根据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,PhotoUploader
end
部分
class Section < ApplicationRecord
belongs_to :collection
has_many :links,dependent: :destroy
end
链接
class Link < ApplicationRecord
belongs_to :section
end
这是建立关系的正确方法,有人可以帮助我了解我所缺少的吗?