Rails / Devise - 如何通过相同的表单创建用户和帖子

时间:2016-02-19 17:21:24

标签: ruby-on-rails ruby devise

我有一个名为user的Devise模型。

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

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

这是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

和user.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"

关于如何获取我的项目索引视图以仅显示属于当前用户的帖子的任何想法?

3 个答案:

答案 0 :(得分:3)

由于您的用户模型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

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:1)

我怀疑您从问题中未配置用户创建以允许嵌套项目参数。您似乎专注于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