控制器#new中的NoMethodError - 未定义方法

时间:2013-05-22 04:55:05

标签: ruby-on-rails ruby-on-rails-3

我在NoMethodError的{​​{1}}行动中收到了new

我的视图中似乎正在访问表单的business_controller对象,然后发生错误:

@business

这是我的新方法:

undefined method `businesses_path' for

我的路线是:

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

mind.blank的建议更改

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

before_filter :check_if_user_has_business, :only => :index

1 个答案:

答案 0 :(得分:1)

您有路线businesses_path还是只有user_businesses_path?如果您只有第二个,那么您应该在表单中指定该URL:

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

此外,如果您设置了正确的关联,那么您可以按如下方式编写if语句:

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

以下是我的写作方式:

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