简体   繁体   English

Controller#new中的NoMethodError-未定义的方法

[英]NoMethodError in controller#new - undefined method

I'm getting a NoMethodError in the new action of my business_controller . 我得到一个NoMethodErrornew我的行动business_controller

It seems to be acessing the @business object for a form in my view and the error occurs then: 在我看来,这似乎是在为表单@business对象,然后发生错误:

undefined method `businesses_path' for

Here is my new method: 这是我的新方法:

def new
  if Business.where(:user_id => current_user.id).first.blank?
    @business = Business.new
  else
    redirect_to user_businesses_path(current_user.id)
  end
end

My routes are: 我的路线是:

  resources :users do
    resources :businesses
      member do
        get 'account'
        post 'payment'
        put 'update_password'
        get 'membership'
      end
  end

mind.blank's suggested changes mind.blank的建议更改

before_filter :check_if_user_has_business, :only => :index

   def new
      @business = Business.new
   end

  private
  def check_if_user_has_business
    redirect_to new_user_business_path(current_user) unless current_user.business
  end

Do you have a route businesses_path or only user_businesses_path ? 您是否有一条路线businesses_path或只有user_businesses_path If you only have the second one then you should specify that URL in your form: 如果只有第二个,则应在表单中指定该URL:

<%= form_for @business, url: user_businesses_path do |f| %>

Also, if you have the correct associations set up, then you can write your if statement as follows: 另外,如果您设置了正确的关联,则可以如下编写if语句:

if current_user.business.nil? # since it's a has_one association

Here's how I would write it: 这是我的写法:

Class BusinessesController < ApplicationController
  before_filter :check_if_user_has_business, only: :new

  def new
    @business = Business.new
  end

  private

  def check_if_user_has_business
    redirect_to user_businesses_path(current_user) if current_user.business
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM