【问题标题】:Rails + jQuery-tokeninput + Draper decorator methodRails + jQuery-tokeninput + Draper 装饰器方法
【发布时间】:2012-05-21 02:23:41
【问题描述】:

我正在使用 Rails + jQuery-tokeninput 执行预输入搜索并填充“belongs_to”关系。这是模型:

class Performance < ActiveRecord::Base
  attr_accessible  :composition_tokens
  belongs_to :composition
    ...
  attr_reader :composition_tokens

  def composition_tokens=(ids) # comma-separated
      self.composition_tokens = ids.split(',')
  end
end

我们在这个项目中使用Draper 为我们的模型提供装饰器。

我们的 CompositionDecorator 有以下方法:

class CompositionDecorator < ApplicationDecorator
  decorates :composition

  def full_title
    model.title + ' by ' + model.composer.canonical_name
  end

我已经设置了 tokeninput 支持来使用装饰器,如下所示:

jQuery ->
  $('#performance_composition_tokens').tokenInput '/admin/compositions.json'
     theme: 'facebook'
     prePopulate:$('#performance_composition_tokens').data('load')
     propertyToSearch: 'full_title'

控制器索引方法像这样调用装饰器:

class Admin::CompositionsController < Admin::BaseController
def index
    @compositions = Composition.includes(:composer).paginate(:page => params[:page]||1)
    respond_to do |format|
      format.html
      format.json { render :json => 
        CompositionDecorator.decorate(@compositions.where("title like ?",
            "%#{params[:q]}%")) }
    end
end

当我不使用装饰器时,这一切似乎都可以正常工作,但是添加装饰器会导致问题。 “full_title”属性未包含在控制器生成的 json 中,因此“未定义”显示在所选值中,搜索结果列表中不显示任何内容。 javascript 控制台中还会显示以下错误:

TypeError: 'undefined' 不是一个对象(评估 'value.replace')

任何帮助将不胜感激!

【问题讨论】:

    标签: ruby-on-rails-3 jquery-tokeninput draper


    【解决方案1】:

    问题是 to_json 不知道对象上的方法,因此您必须通过 :methods 参数明确告诉它。我以前没有使用过 Draper,但看起来您可以在 CompositionDecorator 中添加自己的自定义 to_json。所以,这样的事情可能会奏效:

    class CompositionDecorator
    
      def to_json
        composition.to_json(:methods => [:full_title])
      end
    
    end
    

    另见:

    【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多