Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

Rails how to select attributes


In my controller I have:

def search
  @kategoris = Kampagner.where("titel like ?", "%#{params[:q]}%")
  @kate = []
  @kategoris.each do |kat|
    h = {}
    kat.attributes.each{|k,v| h[k] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v }
    @kate << h
  end
  respond_to do |format|
  format.html
  format.json { render :json => @kate }
  end
end

But the problem is just that all of the attributes for the model are in the JSON data. I only what the attributes ID and title to be in the JSON data. How do I select this?


Solution

  • I'm not very clear why you want to use force_encoding. But you can simply just call:

    format.json { render :json => @kategoris }
    

    Rails will call the method as_json behind the scene. Then in the Kampagner class you can customize the as_json class to control what will be exposed when the record was exported to JSON:

    class Kampagner
      def as_json(options={})
        super(options.merge({ :only => [:id, :title]})
      end
    end
    

    See more: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html