Rails beginner
Rails beginner

Reputation: 14504

Rails easyist way to create hash with certain attributes and also nested

In my controller I have:

  def search
  @sog = Konkurrencer.where("titel like ?", "%#{params[:q]}%")
  @kate = []
  @sog.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

The problem is that the JSON contains all the attributes for the model. How do I create a JSON that have only ID, url and titel?

The JSON should also contain the key "url" which key should be the URL for the associated photo. I use paperclip. The path is: @konkurrencer.photo.image.url

UPDATE: My search.json.erb:

[
<% @sog.each do |kon| %>
{"id":"<%= kon.id %>","titel":"<%= kon.titel %>"},
<% end %>
]

How do I remove the , for the last loop?

Upvotes: 0

Views: 597

Answers (1)

Baldrick
Baldrick

Reputation: 24340

Create an array with the list of attributes you want to display. Use select query method to get only this fields in the SQL request. And finally loop on this attributes to fill the JSON array:

def search
  displayed_attributes = %w{id url titel}

  @sog = Konkurrencer.select(displayed_attributes.join(',')).where("titel like ?", "%#{params[:q]}%")
  @kate = []
  @sog.each do |kat|
    h = {}
    displayed_attributes.each do |attribute| 
       v = kat[attribute]
       h[attribute] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v
    end
    @kate << h
  end
  respond_to do |format|
    format.html
    format.json { render :json => @kate }
  end
end

Upvotes: 1

Related Questions