json - How to write if statement in Rails 4 as_json method? -


i'm using rails 4.i'm creating api databse users can sign facebook graph api. if user has no profile picture image_url null.

after reading answers in thought correct way how build custom json response.

i have created method as_json render response when user created parameters should returned. method how i'm creating json response:

  def as_json(options={}){          id: self.id,         first_name: self.first_name,         last_name: self.last_name,         auth_token: self.auth_token,         image: {             thumb: "http://domain.com" + self.profile_image.thumb.url         }     }     end 

this method above gives me error: no implicit conversion of nil string.

i need give absolute image url path if image exists in db, don't need give parameter in response if image url null in database. how can write if statement inside as_json method? i've tried this, doesn't work.

  def as_json(options={}){          id: self.id,         first_name: self.first_name,         last_name: self.last_name,         auth_token: self.auth_token,         if !self.profile_image.thumb.url == nil             image: {                 thumb: "http://domain.com" + self.profile_image.thumb.url             }         end          }     end 

with jorge de los santos i've managed make pass no implicit conversion of nil string error code:

def as_json(options={})   response = {  id: self.id,                 first_name: self.first_name,                 last_name: self.last_name,                 auth_token: self.auth_token }   if !self.profile_image.thumb.url == nil     image = "http://domain.com" + self.profile_image.thumb.url     response.merge(image: {thumb: image })   end   response end 

but users returned without image parameter when has image url.

your code seems fine except when try merge image key, merge function not working expect, check followingt understand:

 hash = {a: 1, b:2 }  hash.merge(b: 3)  puts hash   #{a: 1, b:2 }  hash = hash.merge(b: 3)  puts hash   #{a: 1, b:2, c: 3 } 

so need modify code changing line:

response.merge(image: {thumb: image }) 

to

response = response.merge(image: {thumb: image }) 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -