使用simple_form_for的URL错误

时间:2014-08-27 19:29:58

标签: ruby-on-rails ruby simple-form

我在生成用于添加和编辑现有用户的表单时遇到问题。它会生成错误的URL以进行提交。我有以下型号:

用户:

class User < ActiveRecord::Base
    has_many :organization_users, :class_name => "::OrganizationUser", :foreign_key => :user_id, :dependent => :destroy
    has_many :organizations, :through => :organization_users
老师:

class User::Teacher < User

组织:

class Organization < ActiveRecord::Base 
    has_many :organization_users
    has_many :users, :through => :organization_users

OrganizationUser:

class OrganizationUser < ActiveRecord::Base
    belongs_to :user, :class_name => "::User"
    belongs_to :organization

在我的路线文件中,我创建了下一条规则:

namespace :manager do
    resources :organizations, :only => [:edit, :update], :controller => "organizations/organizations" do
          resources :users, :only => [:index, :show, :new, :create, :edit, :update, :destroy] do
  end
end

用户控制器如下所示:

class Manager::UsersController < Manager::ApplicationController
      def new
        @user = user_scope.new
        respond_to do |format|
           format.html
        end
      end
      def edit
          respond_to do |format|
              format.html
          end
      end

这是我创建的形式:

= simple_form_for [:manager, @organization, @user], :as => :user, :html => {:class => 'form-horizontal', :multipart => true} do |f|
    = f.input :type, :as => :hidden, :input_html => {:name => :type, :value => @type}
    %ul{:class=>%w(nav nav-tabs)}
    ......

使用此表单,我可以毫无问题地创建新用户。问题是更新现有的,出现此错误:

undefined method `manager_organization_user_teacher_path'

我不知道为什么simple_form正在生成具有用户类型(教师)的网址,此路径不存在。我该如何避免这种行为?

谢谢!

编辑

这里我展示了如何加载@user

UserController:

class Manager::UsersController < Manager::ApplicationController
    require_power_check

    power :crud => :users, :as => :user_scope

    before_filter :load_record, :only => [:show,:edit,:update,:destroy]

  def load_record
      @user = user_scope.find(params[:id])
  end

以下是我的用户范围权限:

    power :users do
        types = []
        types << 'User::Teacher' if can_organization_teacher_index?
        types << 'User::Student' if can_organization_student_index?
        types << 'User::Parent' if can_organization_parent_index?
        User.active.where("type in      (?)",types).includes(:organization_users).where('organization_users.organization_id'=>@organization)
    end

我已经尝试过MaximusDominus解决方案并且它可以正常工作,但是知道它为什么会发生这种情况会很好。

1 个答案:

答案 0 :(得分:0)

在您的新操作中,@userUser

在您的修改操作中,@userUser::Teacher

我们需要了解您如何加载@user资源,以了解您获取User :: Teacher而非用户的原因。

对此最简单的解决方法是becomes方法:

= simple_form_for [:manager, @organization, @user.becomes(User)], :as => :user...

请参阅http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes