如何在rails中将current_user添加到user_id到form_for?

问题描述 投票:11回答:4

我有一个用于创建材料的表单(标题,描述和内容 - 所有基础)。表单保存这些细节很好,但它不保存user_id,user_id应该是current_user的user_id。我该怎么做呢?这一定很容易但到目前为止还没有任何工作。

def create 
   @material = Material.new(params[:material])
   if @material.save
     flash[:success] = "Content Successfully Created"
     redirect_to @material
   else
     render 'new'
   end
end
ruby-on-rails form-for
4个回答
11
投票
def create 
 @material = Material.new(params[:material])
 @material.user_id = current_user.id if current_user
 if @material.save
  flash[:success] = "Content Successfully Created"
  redirect_to @material
 else
  render 'new'
 end
end

4
投票

根据您的应用程序设置方式,有几种不同的方法可以执行此操作。如果用户和材料之间存在关系(用户有许多材料),您可以在控制器中使用它:

def create
  @material = current_user.materials.new(params[:material])
  # ...
end

如果你没有这种关系,我仍然建议在控制器中设置它而不是表单中的隐藏字段。这样会更安全,因为它不会让某人篡改用户ID值:

def create
  @material = Material.new(params[:material].merge(user_id: current_user))
  # ...
end

2
投票

假设您在current_user中保存登录用户的对象,以下将适合您

   @material = Material.new(params[:material])
   @material.user_id = current_user.id
   if @material.save

0
投票

使用Rails 5和参数需要在创建对象之前进行permitted,这是将current_user合并到params中的最简单方法,在他的回答中赞美@Peter Brown:

def create
  @discussion = current_user.materials.new(new_material_params)
  # ...
end

private
def new_material_params
  params.require(:material).permit(:title, :description,: content)
end

如果使用accepts_nested_attributes_for创建嵌套对象,则需要手动合并到关联参数中:

class User < ApplicationRecord
  has_many :discussions # Used to associate User with Discussion later
end

class Comment < ApplicationRecord
  belongs_to :user
end

class Discussion < ApplicationRecord
  belongs_to :user
  has_many :comments
  accepts_nested_attributes_for :comments
end

class DiscussionsController < ApplicationController
  def create
    # Merge the params[:discussion][:user_id] by using the relationship's #new
    @discussion = current_user.discussion.new(new_discussion_params)
  end

  private
  # Sanitized params for creation, not editing
  def new_discussion_params
    params.require(:discussion)
      .permit(:title, :user_id, 
              comments_attributes: [:id, :content, :discussion_id, :user_id])
      .tap do |discussion_params|
        # Require the association parameters, and if they exist,
        # set :user_id for each.
        discussion_params.require(:comments_attributes).each do |i, comment|
          comment.merge!(user_id: current_user.id)
        end
    end
  end
end

抬头:设置(或覆盖!)将是什么params[:discussion][:comments_attributes]["0"][:user_id]适合创作。但是如果除了创建之外还允许编辑深层次结构,请确保不会意外地用当前用户覆盖所有:user_ids。

© www.soinside.com 2019 - 2024. All rights reserved.