Rails неопределенный метод `model_name' в частичной форме

У меня есть эта модель:

class ToType < ActiveRecord::Base
  attr_accessible :Name, :TYP_CCM, :TYP_CCM_TAX, :TYP_CDS_ID, :TYP_CTM, :TYP_CYLINDERS, :TYP_DOORS, :TYP_HP_FROM, :TYP_HP_UPTO, :TYP_ID, :TYP_KV_ABS_DES_ID, :TYP_KV_ASR_DES_ID, :TYP_KV_AXLE_DES_ID, :TYP_KV_BODY_DES_ID, :TYP_KV_BRAKE_SYST_DES_ID, :TYP_KV_BRAKE_TYPE_DES_ID, :TYP_KV_CATALYST_DES_ID, :TYP_KV_DRIVE_DES_ID, :TYP_KV_ENGINE_DES_ID, :TYP_KV_FUEL_DES_ID, :TYP_KV_FUEL_SUPPLY_DES_ID, :TYP_KV_MODEL_DES_ID, :TYP_KV_STEERING_DES_ID, :TYP_KV_STEERING_SIDE_DES_ID, :TYP_KV_TRANS_DES_ID, :TYP_KV_VOLTAGE_DES_ID, :TYP_KW_FROM, :TYP_KW_UPTO, :TYP_LA_CTM, :TYP_LITRES, :TYP_MAX_WEIGHT, :TYP_MMT_CDS_ID, :TYP_MOD_ID, :TYP_PCON_END, :TYP_PCON_START, :TYP_RT_EXISTS, :TYP_SORT, :TYP_TANK, :TYP_VALVES, :is_in_to
  set_primary_key :TYP_ID
  belongs_to :to_model
  has_many :to_articles, :foreign_key => "to_type_id", :dependent => :destroy
end

class ToArticle < ActiveRecord::Base
  attr_accessible :details, :manufacturer, :name, :oem_number, :only_with_vin, :quantity, :to_type_id
  belongs_to :to_type, :foreign_key => "TYP_ID"
  belongs_to :to_engine
end

(некоторые базы данных конвертируются из большого каталога, поэтому правила рельсов немного несовершенны)

Часть моего представления представления to_type:

%td
            = link_to "Подробнее", admin_catalog_to_to_article_path(c), :class=>'btn btn-primary'
            = link_to "Редактирование", edit_admin_catalog_to_to_type_path(c), :class=>'btn btn-warning'
            = link_to "Удалить", admin_catalog_to_to_type_path(c), :confirm => "!!!Тип #{c.Name} будет удалён!!!! Вы уверены?", :method => :delete, :class => "btn btn-danger"

мое действие show работает нормально для моего контроллера:

class Admin::Catalog::To::ToTypesController < ApplicationController
  respond_to :html

  before_filter :auth_user

  def auth_user
    redirect_to new_admin_session_path unless admin_signed_in?
  end

  def show
    @mod_id = params[:id]
    @man = ToType.find(:all, conditions: {:TYP_MOD_ID => @mod_id}, order: "Name ASC")
    render :layout => 'admin'
  end

  def edit
    @man = ToType.find(params[:id])
    render :layout => 'admin'
  end

  def update
    @man = ToType.find(params[:id])
    if @mod.update_attributes(params[:to_type])
      redirect_to admin_catalog_to_to_type_path(@man.TYP_MOD_ID)
    else
      render :layout => 'admin'
    end
  end

  def new
    @man = ToType.new
    @mod_id = params[:mod_id]
    render :layout => 'admin'
  end

  def create
    @man = ToType.new(params[:to_type])
    @mod_id = params[:mod_id]
    @man.TYP_MOD_ID = @mod_id
    if @man.save
      redirect_to admin_catalog_to_to_type_path(@mod_id)
    else
      render :layout => 'admin'
    end
  end

  def destroy
    @man = ToType.find(params[:id])
    if @man.destroy
      redirect_to admin_catalog_to_to_type_path(@man.TYP_MOD_ID)
    else
      render :layout => 'admin'
    end
  end
end

and route:

namespace :admin do
  namespace :catalog do
      namespace :to do
        resources :to_manufacturers, 
                  :to_models, 
                  :to_types, 
                  :to_articles
      end
    end

  end

частичная форма:

= form_for [:admin, :catalog, :to, @man] do |f|
  = f.label :id
...

Когда я пытаюсь изменить или создать, я получаю:

undefined method `model_name' for NilClass:Class

Я думаю, что что-то не так со связью с моделью: с обновлением и созданием. В журнале я вижу, что объект основан в базе данных для редактирования, например, и в журнале я вижу, что @man не пуст, но я все равно получаю undefined methodmodel_name' для NilClass:Class` . Почему?

обновление: полная трассировка

        NoMethodError in Admin/catalog/to/to_types#edit

Showing /media/sf__Projects/Denis/app/views/admin/catalog/to/to_types/_edit.html.haml where line #1 raised:

undefined method `model_name' for NilClass:Class
Extracted source (around line #1):

1: = form_for [:admin, :catalog, :to, @man] do |f|
2:   = f.label :id
Trace of template inclusion: app/views/admin/catalog/to/to_types/edit.html.haml

Rails.root: /media/sf__Projects/Denis

Application Trace | Framework Trace | Full Trace
activemodel (3.2.8) lib/active_model/naming.rb:163:in `model_name_from_record_or_class'
activemodel (3.2.8) lib/active_model/naming.rb:158:in `param_key'
actionpack (3.2.8) lib/action_view/helpers/form_helper.rb:369:in `form_for'
haml (4.0.3) lib/haml/helpers/action_view_mods.rb:146:in `form_for_with_haml'
haml (4.0.3) lib/haml/helpers/action_view_xss_mods.rb:28:in `form_for_with_haml_xss'
app/views/admin/catalog/to/to_types/_edit.html.haml:1:in `_app_views_admin_catalog_to_to_types__edit_html_haml___4584370517694291299_51970960'
actionpack (3.2.8) lib/action_view/template.rb:145:in `block in render'
activesupport (3.2.8) lib/active_support/notifications.rb:125:in `instrument'
actionpack (3.2.8) lib/action_view/template.rb:143:in `render'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:265:in `render_partial'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:238:in `block in render'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/partial_renderer.rb:237:in `render'
actionpack (3.2.8) lib/action_view/renderer/renderer.rb:41:in `render_partial'
actionpack (3.2.8) lib/action_view/helpers/rendering_helper.rb:27:in `render'
haml (4.0.3) lib/haml/helpers/action_view_mods.rb:10:in `block in render_with_haml'
haml (4.0.3) lib/haml/helpers.rb:89:in `non_haml'
haml (4.0.3) lib/haml/helpers/action_view_mods.rb:10:in `render_with_haml'
app/views/admin/catalog/to/to_types/edit.html.haml:7:in `_app_views_admin_catalog_to_to_types_edit_html_haml___2140731807560860717_28965400'
actionpack (3.2.8) lib/action_view/template.rb:145:in `block in render'
activesupport (3.2.8) lib/active_support/notifications.rb:125:in `instrument'
actionpack (3.2.8) lib/action_view/template.rb:143:in `render'
actionpack (3.2.8) lib/action_view/renderer/template_renderer.rb:47:in `block (2 levels) in render_template'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
actionpack (3.2.8) lib/action_view/renderer/template_renderer.rb:46:in `block in render_template'
actionpack (3.2.8) lib/action_view/renderer/template_renderer.rb:54:in `render_with_layout'
actionpack (3.2.8) lib/action_view/renderer/template_renderer.rb:45:in `render_template'
actionpack (3.2.8) lib/action_view/renderer/template_renderer.rb:18:in `render'
actionpack (3.2.8) lib/action_view/renderer/renderer.rb:36:in `render_template'
actionpack (3.2.8) lib/action_view/renderer/renderer.rb:17:in `render'
actionpack (3.2.8) lib/abstract_controller/rendering.rb:110:in `_render_template'
actionpack (3.2.8) lib/action_controller/metal/streaming.rb:225:in `_render_template'
actionpack (3.2.8) lib/abstract_controller/rendering.rb:103:in `render_to_body'
actionpack (3.2.8) lib/action_controller/metal/renderers.rb:28:in `render_to_body'
actionpack (3.2.8) lib/action_controller/metal/compatibility.rb:50:in `render_to_body'
actionpack (3.2.8) lib/abstract_controller/rendering.rb:88:in `render'
actionpack (3.2.8) lib/action_controller/metal/rendering.rb:16:in `render'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:40:in `block (2 levels) in render'
activesupport (3.2.8) lib/active_support/core_ext/benchmark.rb:5:in `block in ms'
/home/pavel/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/1.9.1/benchmark.rb:295:in `realtime'
activesupport (3.2.8) lib/active_support/core_ext/benchmark.rb:5:in `ms'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:40:in `block in render'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:83:in `cleanup_view_runtime'
activerecord (3.2.8) lib/active_record/railties/controller_runtime.rb:24:in `cleanup_view_runtime'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:39:in `render'
app/controllers/admin/catalog/to/to_types_controller.rb:18:in `edit'
actionpack (3.2.8) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.8) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.8) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.8) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.2.8) lib/active_support/callbacks.rb:447:in `_run__3422493215220642812__process_action__1624115620138968240__callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.8) lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.8) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.2.8) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.8) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.8) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.8) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.2.8) lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
activerecord (3.2.8) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (3.2.8) lib/abstract_controller/base.rb:121:in `process'
actionpack (3.2.8) lib/abstract_controller/rendering.rb:45:in `process'
actionpack (3.2.8) lib/action_controller/metal.rb:203:in `dispatch'
actionpack (3.2.8) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.2.8) lib/action_controller/metal.rb:246:in `block in action'
actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:73:in `call'
actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:36:in `call'
journey (1.0.4) lib/journey/router.rb:68:in `block in call'
journey (1.0.4) lib/journey/router.rb:56:in `each'
journey (1.0.4) lib/journey/router.rb:56:in `call'
actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:600:in `call'
warden (1.2.1) lib/warden/manager.rb:35:in `block in call'
warden (1.2.1) lib/warden/manager.rb:34:in `catch'
warden (1.2.1) lib/warden/manager.rb:34:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
rack (1.4.5) lib/rack/etag.rb:23:in `call'
rack (1.4.5) lib/rack/conditionalget.rb:25:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/head.rb:14:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/flash.rb:242:in `call'
rack (1.4.5) lib/rack/session/abstract/id.rb:210:in `context'
rack (1.4.5) lib/rack/session/abstract/id.rb:205:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/cookies.rb:339:in `call'
activerecord (3.2.8) lib/active_record/query_cache.rb:64:in `call'
activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_pool.rb:473:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `_run__2440713806940417433__call__2360308109704352565__callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.8) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.8) lib/rails/rack/logger.rb:26:in `call_app'
railties (3.2.8) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.5) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.5) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.8) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.5) lib/rack/lock.rb:15:in `call'
actionpack (3.2.8) lib/action_dispatch/middleware/static.rb:62:in `call'
railties (3.2.8) lib/rails/engine.rb:479:in `call'
railties (3.2.8) lib/rails/application.rb:223:in `call'
rack (1.4.5) lib/rack/content_length.rb:14:in `call'
railties (3.2.8) lib/rails/rack/log_tailer.rb:17:in `call'
rack (1.4.5) lib/rack/handler/webrick.rb:59:in `service'
/home/pavel/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/home/pavel/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/home/pavel/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'
Request

Parameters:

{"id"=>"28752"}
Show session dump

Show env dump

Response

Headers:

None

person brabertaser19    schedule 01.08.2013    source источник
comment
также пытаюсь переименовать в to_engines: не помогло... не понял почему? (   -  person brabertaser19    schedule 02.08.2013
comment
Ошибка говорит, что у вас есть nil, когда вы ожидаете объект. В коде редактирования вы не проверяете, возвращает ли функция find() запись. Что произойдет, если вы передадите идентификатор, которого нет в базе данных?   -  person Fred    schedule 02.08.2013
comment
@Fred, но я вижу, что из БД он выбирает данные   -  person brabertaser19    schedule 02.08.2013
comment
@Фред, так что ты думаешь?   -  person brabertaser19    schedule 02.08.2013
comment
Учитывая то, что у вас здесь, вложенные ресурсы выглядят странно. Я не понимаю, почему у вас есть несколько объявлений пространства имен :catalogs под администратором (и несколько объявлений :to и т. д.). Возможно, это путает рельсы? Просто предложение.   -  person Fred    schedule 02.08.2013
comment
@Fred, это было создано с помощью rails g scaffold Admin/Catalog/To/Manufacturer, например: да, это выглядит не так хорошо, но это сделано с помощью генераторов rails, как и что я могу изменить?   -  person brabertaser19    schedule 02.08.2013
comment
@Fred в пространстве имен администратора мне нужно иметь еще два пространства имен: catalog и to, все остальные должны быть ресурсами: но я не знаю, как сделать такую ​​глубокую вложенность, что писать в маршрутах, что в контроллерах, как использовать генераторы потому что все учебники в сети очень просты, я никогда не видел, как работать с глубокой вложенностью   -  person brabertaser19    schedule 02.08.2013
comment
Чтобы изменить его, просто отредактируйте файл route.rb. Строительные леса — это только отправная точка. Или переосмыслите глубоко вложенные пространства имен и попробуйте другой дизайн; очевидно, я не могу понять обоснование вашего дизайна из того, что здесь мало информации, поэтому я не знаю, насколько это сложно.   -  person Fred    schedule 02.08.2013
comment
@Fred хорошо ... плохо, что я не могу понять, почему все модели работают, а только эта нет (   -  person brabertaser19    schedule 02.08.2013
comment
@Fred также показывает, что просмотры индекса работают нормально   -  person brabertaser19    schedule 02.08.2013
comment
давайте продолжим это обсуждение в чате   -  person Fred    schedule 02.08.2013
comment
@Fred также взгляните на stackoverflow.com/questions/18215087/   -  person brabertaser19    schedule 14.08.2013
comment
Что вы имеете в виду, говоря, что я думаю, что что-то не так со связью с моделью: с обновлением и созданием?   -  person Btuman    schedule 14.08.2013
comment
Кроме того, не могли бы вы указать точные имена файлов   -  person Btuman    schedule 14.08.2013
comment
@Btuman, что ты имеешь в виду?   -  person brabertaser19    schedule 14.08.2013
comment
Я не уверен, что вы имеете в виду под этим предложением, я также хотел увидеть точные имена файлов.   -  person Btuman    schedule 14.08.2013
comment
@Btuman Где точные имена файлов? )) извините, я не понял, что вы хотите   -  person brabertaser19    schedule 14.08.2013
comment
давайте продолжим это обсуждение в чате   -  person Btuman    schedule 14.08.2013
comment
@brabertaser1992 brabertaser1992 ты умеешь пользоваться отладчиком? если да, поставьте отладчик перед form_for и проверьте, присутствует ли '@man'?, каково его значение?   -  person Sachin Singh    schedule 16.08.2013
comment
@SachinSingh я почти решил это, какая-то проблема с моделью, если я удалю связь типа с моделью, все в порядке   -  person brabertaser19    schedule 17.08.2013


Ответы (2)


Выглядит слишком просто, но где определяется @typ? У вас есть @typ в частичном, но @man в контроллере.

person zrl3dx    schedule 14.08.2013
comment
извините, это другой частичный... новый есть другой объект, когда это один и тот же объект, я получаю сообщение об ошибке.. я отредактировал вопрос - person brabertaser19; 14.08.2013
comment
так что вы думаете сейчас? - person brabertaser19; 14.08.2013
comment
Попробуйте протестировать его с помощью form_for [:admin, :catalog, :to, ToType.new] и покажите результат. - person zrl3dx; 14.08.2013
comment
Извините, забыл про пространство имен, попробуйте: Admin::Catalog::To::ToType.new вместо ToType.new. - person zrl3dx; 14.08.2013
comment
pastebin.com/ziUn1Zj4 также я пытаюсь = form_for [:admin, :catalog, :to, Admin::Catalog ::To::ToType.new] сделать |f| - person brabertaser19; 14.08.2013
comment
Ожидается, что /media/sf__Projects/Denis/app/models/to_type.rb также определит ToType, почему тогда шоу работает? также у меня есть эта модель в папке с моделью без какой-либо подпапки ... ToManu-s и ToModels одинаковы, но есть рабочие, но это нет (какая магия ()) - person brabertaser19; 14.08.2013
comment
Мой последний комментарий был неправильным, это привело бы к слишком большому беспорядку, проверьте выход в корневую область в контроллере, добавив :: к ToType.new, чтобы вы получили ::ToType.new. - person zrl3dx; 14.08.2013
comment
хм (до сих пор не определен метод `model_name' для NilClass:Class, может быть, teamviewer? - person brabertaser19; 14.08.2013
comment
давайте продолжим это обсуждение в чате - person brabertaser19; 14.08.2013

У вас есть это в вашей форме form_for [:admin, :catalog, :to, @typ], но у вас нет объекта @typ - у вас есть @man

person link_er    schedule 14.08.2013
comment
извините, это другой частичный... новый есть другой объект, когда это один и тот же объект, я получаю сообщение об ошибке.. я отредактировал вопрос - person brabertaser19; 14.08.2013
comment
а что такое fulltrace ошибки сейчас? у вас все еще есть @typ там - person link_er; 14.08.2013
comment
@yes, я обновил код, забудь об этих именах (я изменил код, забыл обновить все здесь), проблема не в этом - person brabertaser19; 14.08.2013
comment
смотри, я немного попробовал переименовать, так что это была небольшая проблема, но ты можешь видеть, что с обычным именем все то же самое. - person brabertaser19; 14.08.2013
comment
Я получил эту ошибку, когда объект, который использовался для формы, был равен нулю. Так что проверьте пожалуйста, что приходит на вашу форму - я вижу код контроллера, но... И попробуйте сделать form_for @man, url: [:admin, :catalog, :to, @man] - может ошибки не будет - person link_er; 14.08.2013
comment
- if [email protected]? = @man вижу #‹ToType:0x00000005f096f0› - person brabertaser19; 14.08.2013
comment
также @man, url: [:admin, :catalog, :to, @man] не помогло( misique - person brabertaser19; 14.08.2013
comment
посмотрите здесь https://github.com/link-er/check_project - person link_er; 14.08.2013
comment
хм, не могу запустить его, мой проект запускается нормально, но при этом говорят, что я должен использовать новое приложение rails и т. д., а также упаковщик не запустился - person brabertaser19; 14.08.2013
comment
Итак, из github, похоже, работает нормально ... в БД он создается, просто я получаю Нет совпадений маршрутов {:action=›show, :controller=›admin/catalog/to/to_types, :id=›nil} - person brabertaser19; 15.08.2013
comment
проверить. были проблемы с полями отсутствия. но главное, что форма работает... так что может у вас где-то опечатки - person link_er; 15.08.2013
comment
хм, я думаю, что форма не работает, если я пишу в частичной форме, я вижу ошибки, даже если я помещаю туда только одно поле) - person brabertaser19; 15.08.2013
comment
хм, странно, когда я комментирую модель типа, как вы, она работает - person brabertaser19; 15.08.2013
comment
хех) то, что мне нужно, это только own_to :to_model, :foreign_key => TYP_MOD_ID - person brabertaser19; 15.08.2013