John Smith
John Smith

Reputation: 6259

:name, :forname to :fullname

Its the first time i work with json in Rails. In the search action from the patients controller i defined:

     format.json { render json: @patients}

So now this resource gives me such a output:

[{"id":73551,"typ":null,"name":"Beck","forname":"Ana","birthday":"1945-06-14","titel":"",department_id":2,"tot":null},

I would like to change the ouput to something like:

[{"id":73551,"fullname":"Beck, Ana"},{...

How do i do this? Thanks!

Update! Now i have:

....
      respond_to do |format|
        format.html {}
        format.json { render json: as_json(@patients)}
      end
  end

  def as_json(options={})
     { 
         :id => self.id,
         :fullname => self.name + ", " + self.forname
     } 
  end

But somehow i get the error

undefined method `id' for #

Upvotes: 0

Views: 73

Answers (1)

select clause should do the work : @patients.select([:id, :fullname, :whateveryouneed])


For the second problem, you may consider overidding Patient.as_json method :

def as_json(options={})
     { 
         :id => self.id,
         :fullname => self.name + ", " + self.forname
     } 
end

Upvotes: 1

Related Questions