【问题标题】:Basic rails crud in ajax with devise带有设计的ajax中的基本rails crud
【发布时间】:2016-10-12 20:33:39
【问题描述】:

我在 rails 和 ajax 中有一个基本的 CRUD,但是我需要集成 Devise gem,当我将 devise gem 添加到我的项目并测试 CRUD 时,我收到了这个错误:

rails 4.2 中的控制器代码:

class ProductsController < ApplicationController

  before_action :authenticate_user!
  before_action :product_find, only: [:show, :update, :destroy, :edit]

  def index
    @products = Product.all.order('created_at DESC')
  end

  def show

  end

  def new
    @product = Product.new

    respond_to do |format|
      format.html { render layout: false }
      format.json { render json: @product }
      format.js
    end

  end

  def create
    @product = current_user.products.build(product_params)
    respond_to do |format|
      if @product.save
        format.json { render :show, status: :created, location: @product}
        format.js
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end

  def edit

  end

  def update
    @product = Product.update(params[:id], product_params)
  end

  def destroy
    @product.destroy
  end

  private

    def product_find
      @product = Product.where(id: params[:id]).first
    end

    def product_params
      params.require(:product).permit(:name, :quantity, :price)
    end
end

用户可以正常连接,当我用注册用户创建新产品时出现错误

我做错了什么?

我认为错误可能在 CREATE 和 NEW 方法中

谢谢!

【问题讨论】:

  • 您确定您的用户在收到错误时已登录?
  • 用户可以正常连接,注册用户创建新产品时出现错误
  • 当你得到错误时是current_user non-null?
  • 我认为错误可能在 CREATE 和 NEW 方法中

标签: ruby-on-rails ajax devise


【解决方案1】:

您是否为模型正确设置了关联?错误undefined method 'products' for &lt;User&gt; 表明您没有。

# user.rb
has_many :products

# product.rb
belongs_to :user

确保您在 Product 模型上也有一个 user_id 字段。

【讨论】:

  • 完全正确!,菜鸟错误,我在新方法中添加 current_user.products.build 并在创建方法中添加 current_user.products.build (product_params) 非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-22
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
相关资源
最近更新 更多