我正在尝试在我的应用程序中创建一个多层控制器。
具有以下结构:
--Business_and_units_controller(主控制器(
--↳ Business_units_controller( 副控制器 (
----↳ Business_managers_controller( 子控制器到Business_units_controller (
----↳ Business_divisions_controller( 子控制器到Business_units_controller (
----↳ business_units_strats_attributes_controller( 子控制器到Business_units_controller (
这很复杂,也许太过分了?
无论如何,我已经创建了名为:
business_and_units_controller.rb
使用模型:
business_and_unit.rb
我已将控制器添加到我的routes.rb(以测试它并查看它是否有效(
get '/testunit', to: 'business_and_units#index'
resources :business_and_units
查看代码是否有效后,我收到以下错误:
NoMethodError in BusinessAndUnitsController#index
undefined method `businessandunits' for #<User:0x007f55666f2a58>
Extracted source (around line #6):
1
2
3
4 def index
6 @business_and_units = current_user.businessandunits
7
8 end
我知道问题的原因是我的business_and_units没有定义。但我不明白为什么没有定义它。
你们中有人能看到我问题的原因吗?
总结一下:
我的问题:根据 ruby 的说法,我的 business_and_units_controller.rb 没有在索引中定义。
这篇文章的目标:理解为什么没有定义它。
ps:我已经搜索了许多类似的帖子来寻找我的问题的解决方案,但无法找到解决方案。
我的控制器文件
class BusinessAndUnitsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
@business_and_units = current_user.business_and_units
end
def show
@business_and_units = Business_and_unit.find_by(id: params[:id])
if !@business_and_unit
raise ActionController::RoutingError.new('Not Found')
end
@user = @business_and_unit.user
end
def new
@user = User.new
@business_and_unit = Business_and_unit.new
end
def edit
@business_and_unit = Business_and_unit.find(params[:id])
end
def create
@business_and_unit = current_user.business_and_units.build(business_and_unit_params)
if @business_and_unit.save
flash[:success] = "business_and_unit created!"
redirect_to @business_and_unit
else
@feed_items = current_user.feed.paginate(page: params[:page])
render 'new'
end
end
def update
@business_and_unit = Business_and_unit.find(params[:id])
if @business_and_unit.update(business_and_unit_params)
redirect_to @business_and_unit
else
render 'edit'
end
end
def destroy
@business_and_unit.destroy
flash[:success] = "business_and_unit deleted"
redirect_to business_and_units_path
end
private
def business_and_unit_params
params.require(:business_and_unit).permit(
:corporate_strategy, :future_sale_value,
:industry, :market_focus, :business_unit,
business_units_attributes: [
:id, :business_units,
:_destroy],
business_managers_attributes: [
:id, :business_managers,
:_destroy],
business_divisions_attributes: [
:id, :business_divisions,
:business_divisions_managers,
:_destroy],
business_units_strats_attributes: [
:id, :business_units_strats,
:_destroy])
end
def correct_user
@business_and_unit = current_user.business_and_units.find_by(id: params[:id])
redirect_to business_and_units_path if @business_and_unit.nil?
end
end
该问题与您的控制器无关。
错误在于User
模型中没有#businessandunits
方法。
根据您提供的信息,我认为您错过了User
课上has_many :business_and_units
的关系定义。
然后您就可以打电话current_user.business_and_units