Ruby on rails 使用嵌套管线创建房屋

Ruby on rails 使用嵌套管线创建房屋,ruby-on-rails,ruby,controller,Ruby On Rails,Ruby,Controller,首先,这是我所有的代码 #models/user.rb class User < ApplicationRecord has_many :trips has_many :homes, through: :trips has_secure_password accepts_nested_attributes_for :trips accepts_nested_attributes_for :homes validates :name, presence: tr

首先,这是我所有的代码

  #models/user.rb
  class User < ApplicationRecord
  has_many :trips
  has_many :homes, through: :trips
  has_secure_password
  accepts_nested_attributes_for :trips
  accepts_nested_attributes_for :homes
  validates :name, presence: true
  validates :email, presence: true
  validates :email, uniqueness: true
  validates :password, presence: true
  validates :password, confirmation: { case_sensitive: true }
end
#models/user.rb
类用户<应用程序记录
你有很多旅行吗
有很多:家,通过::旅行
有安全的密码吗
接受以下内容的\u嵌套\u属性\u:trips
接受家庭的\u嵌套\u属性\u
验证:名称,状态:true
验证:电子邮件,状态:true
验证:电子邮件,唯一性:true
验证:密码,状态:true
验证:密码,确认:{区分大小写:true}
结束
#home.rb
类主页<应用程序记录
你有很多旅行吗
有很多:用户,通过::trips
验证:地址,状态:true
结束
class HomesController
我正在尝试这样做,以便创建的主页与创建它的用户相关联

  def create
    @user = User.find_by(id: params[:user_id])
    @home = Home.new(home_params)
    if @home.save
      @user.homes << @home
    else
      render :new
    end
  end
def创建
@user=user.find_by(id:params[:user_id])
@主页=主页。新建(主页参数)
如果@home.save

@user.homes当前用户创建资源的典型方式是使用诸如designe之类的身份验证,而不是嵌套资源。而是通过身份验证系统获取控制器中的当前用户,并从中构建资源:

resources :homes

class HomesController
这将在处理API时,从会话或类似访问令牌的内容设置模型(本例中为Trip-join模型)上的
用户id

当您作为特定用户创建资源时,不希望嵌套资源的原因是传递另一个用户id以作为另一个用户创建资源很简单。会话cookie是加密的,因此更难篡改,身份验证令牌也是如此


通过使用
if-params[:user\u id]
user.find\u by(id:params[:user\u id])
你实际上是在给自己一个潜在的零错误,并对自己的脚开枪。如果某个操作需要记录用户,请在执行该操作之前使用
回调,以确保他们已通过身份验证,并引发错误并退出(将用户重定向到登录)。这就是像Desive、Knock和Sorcery这样的认证宝石如何处理它。

研究使用像Desive这样的授权系统,它将用户id存储在加密的会话cookie中。您不应该从此处的参数中接受用户id,因为这会使恶意用户传递任何id,从而以其他用户的身份创建资源或编辑其他用户资源变得微不足道。我在我的控制器目录中的应用程序\u controller.rb中定义了当前的\u user方法。我不知道如何在我的家庭控制器中访问它。我试过很多东西。有什么线索吗?
  def create
    @user = User.find_by(id: params[:user_id])
    @home = Home.new(home_params)
    if @home.save
      @user.homes << @home
    else
      render :new
    end
  end
resources :homes

class HomesController < ApplicationController

  ...

  # GET /homes/new
  def new
    @home = current_user.homes.new
  end

  # POST /homes
  def create
    @home = current_user.homes.new(home_parameters)
    if @home.save
      redirect_to @home
    else
      render :new
    end
  end

  ...
end