【问题标题】:Rails/ Devise - How to Create a User and a Post Through the Same formRails/ Devise - 如何通过同一个表单创建用户和帖子
【发布时间】:2016-02-19 17:21:24
【问题描述】:

我有一个名为 user 的设计模型。

我还有一个名为项目的模型。

我希望用户在创建用户帐户时创建一个项目。我的功能正常工作;但是,用户项目没有保存到数据库中。

这里是 projects_controller.rb

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  # GET /projects
  # GET /projects.json
  def index
    @projects = current_user.projects
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)
    @project.user = current_user
    respond_to do |format|
      if @project.save
        format.html { redirect_to root_path, notice: 'Thanks! Your project has been saved. Please check your email inbox now.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:service, :location, :details, :email)
    end
end

和用户.rb

class User < ActiveRecord::Base
  has_many :projects, :dependent => :destroy
  accepts_nested_attributes_for :projects, :reject_if => lambda { |a| a[:content].blank}, allow_destroy: true
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
end

和项目模型

class Project < ActiveRecord::Base
  belongs_to :user
end

以及创建用户/他们的第一个帖子的表单

= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |u|

  = devise_error_messages!

  = u.fields_for :project do |p|
    .field = p.text_field :service, placeholder: "What service do you need?"
    .field = p.text_field :location, placeholder: "What's the project location?"


  .field = u.email_field :email, autofocus: true, placeholder: "What's your email address?"

  .actions = u.submit "Click to continue"

关于如何让我的项目索引视图仅显示属于当前用户的帖子有什么想法吗?

【问题讨论】:

  • 您尝试创建用户帐户的部分在哪里?帖子控制器与您的问题有什么关系,您提到的是用户、用户帐户和项目而不是帖子?
  • 错字 - 帖子应该是项目。

标签: ruby-on-rails ruby devise


【解决方案1】:

由于您的用户模型 has_many 项目,您需要将表单修改为

 = u.fields_for :projects do |p|
   .field = p.text_field :service, placeholder: "What service do you need?"
   .field = p.text_field :location, placeholder: "What's the project location?"

并在您的应用程序控制器中添加 projects_attributes 到用户允许的参数中,为此使用一个块

before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(projects_attributes: [:service, :location])
    end
  end

更多信息请查看

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

https://github.com/plataformatec/devise/blob/7b33a8ef5749e0b593d785a1cd4787d2979cdee5/lib/devise/parameter_sanitizer.rb

【讨论】:

【解决方案2】:

当您创建帖子时,您并没有传递用户。您可以在保存之前传入用户:

@project = Project.new(params[:project])
@project.user = current_user

或者您可以根据关系创建帖子:

@project = current_user.posts.new(params[:project])

【讨论】:

  • 添加了@project.user = current_user ...但数据仍然没有保存/显示在项目索引视图中
  • 在rails控制台中,运行Post.last.user会得到什么?
  • 跑了 Project.last.user (没有后期模型),它返回 nil
  • 好的,您的表单实际上是发布到注册控制器,而不是项目控制器。我不认为我的回答会对你有所帮助。您尝试这样做的方式,您可能需要覆盖默认设计控制器,并更改您的路线以匹配。 Configuring Controllers 下的设计自述文件中有更多信息
  • 这是正确的 - 我正在覆盖默认的设计注册控制器以接受项目属性并在用户完成注册时创建一个项目。
【解决方案3】:

我从您的问题中怀疑您没有配置用户创建以允许您的嵌套项目参数。您似乎专注于 Project 控制器和代码,但您的用户将由 Devise::RegistrationsController 创建(除非您指定了自己的版本)。

您需要告诉设计您将允许用户创建哪些参数(请参阅Devise Strong Parameters

你可能需要这样的东西:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [project_attributes: [:service, :location]])
  end
end

for devise 3:

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) << { project_attributes: [:service, :location] }
end

【讨论】:

  • 我在尝试该代码时收到以下错误:private method permit called for #&lt;Devise::ParameterSanitizer:0x007fa2f3d01bd0&gt;
  • 我添加了一些适用于设计 3 的内容(以及相关文档的链接)
  • 尝试添加,但项目数据仍未保存,我的日志中出现此错误:Unpermitted parameter: project
  • 你可能只需要project: 而不是project_attributes:
  • 改项目后还是报同样的错误:
猜你喜欢
  • 2020-11-16
  • 2012-06-17
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
相关资源
最近更新 更多