【问题标题】:Rails: undefined method `model_name' for nil:NilClassRails:nil的未定义方法`model_name':NilClass
【发布时间】:2015-05-30 05:16:51
【问题描述】:

如何在仍然能够从控制器和模型中获取用户信息的同时创建单独的页面?

例如,我希望有单独的页面,但仍使用来自产品控制器的相同信息。

views/product/order.html.erb

然而,当我添加一个 simple_form_for 时,我得到一个错误

<%= simple_form_for(@products) do |f| %>

基本上我想要的只是一个单独的页面来提交产品信息。如果不是,我很乐意在同一个页面中执行此操作,并拥有像这样的旋转 simple_form,而无需创建多个页面。

http://malsup.com/jquery/cycle/

例子:

products_controller.rb

class ProductsController < ApplicationController
 before_action :set_product, only: [:show, :edit, :update, :destroy]

def index
@products = Product.where(availability: true)
  respond_with(@products)
end


def show
end


def new
  @product = Product.new
end


def edit
  authorize! :manage, @product
end


def create
    @product = current_user.products.new(product_params)
  @product.save
  respond_with(@product)
end


def update
    authorize! :manage, @product
  respond_to do |format|
    if @product.update(product_params)
      format.html { redirect_to @product, notice: 'Product was successfully updated.' }
      format.json { render :show, status: :ok, location: @product }
    else
      format.html { render :edit }
      format.json { render json: @product.errors, status: :unprocessable_entity }
    end
  end
end

def destroy
    authorize! :manage, @product
  @product.destroy
  respond_to do |format|
    format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
    format.json { head :no_content }
  end
end

【问题讨论】:

  • 粘贴你的控制器代码
  • 你确定它的@products&lt;%= simple_form_for(@products) do |f| %&gt; 中吗?

标签: jquery ruby-on-rails ruby


【解决方案1】:
<%= simple_form_for(@product) do |f| %>

使用@product 代替@products

将以下内容添加到 products_controller.rb

def order
  @product = Product.new
end

【讨论】:

  • 我仍然收到undefined method model_name for nil:NilClass,我已经更新了问题中的一个示例。如何在不必创建新页面的情况下做到这一点,例如通过按下顶部的气泡让表单滑动?
  • 你的方法 order 在你的 products_controller 中定义在哪里?
  • 我没有定义顺序,我只是想到了一个随机页面
  • 在你的 congig/routes.rb 中尝试resources :products
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多