inherited_resources 常见用法 - tianlu1677/tianlu1677.github.io GitHub Wiki

请使用版本大于1.6.0 这样才支持namespace

安装

gem 'inherited_resources'

class ProjectsController < InheritedResources::Base
  # or inherit_resources
  respond_to :html, :xml, :json
  respond_to :js, :only => :create
  respond_to :iphone, :except => [ :edit, :update ]
end

生成常见的内容

resource        #=> @project
collection      #=> @projects
resource_class  #=> Project
parent      # @task
parent_class  # Task
parent?    # true
parent_type  # :task

覆盖源代码中的collection 参数

class ProjectsController < InheritedResources::Base
  protected
    def collection
      get_collection_ivar || set_collection_ivar(end_of_association_chain.paginate(:page => params[:page]))
    end

    def begin_of_association_chain
      @current_user
    end
end

调用父类的方法

def destroy
    super do |format|
      format.html { redirect_to root_url }
    end
end

# 失败执行内容 和 成功执行内容
update! do |success, failure|
  failure.html { redirect_to project_url(@project) }
 end

实现关联


belongs_to :task, :file, :message, :optional => true
belongs_to :manager, :singleton => true
belongs_to :task, :file, :message, :polymorphic => true

# 或者

belongs_to :project do
    belongs_to :task, :file, :message, :polymorphic => true
end