Ruby format.json add text to model column -
i add text model when json object returned. example
format.json { render :json => @user.to_json, :status => 200 }
the @user model contains field called website. user websites in format www.mysite.com, want resulting json display http://www.mymysite.com.
for example, there thousands of users.
@users = user.all format.json { render :json => @users.to_json, :status => 200 }
i don't want go through users , update website column 1 one. there way define in model returned value of website http:// + self.website?
the more research looks override method def as_json(options = {}), i'm not sure how modify website field.
you can have method following in user
model class (app/model/user.rb
):
def website_with_protocol "http://#{self.website}" end
then, able do: @user.website_with_protocol
user's website http://
in beginning.
or, if don't mind, can override website
column in database defining website
method in model class this:
def website "http://#{self.read_attribute(:website)}" end
so, if call: @user.website
, give this: http://www.mymysite.com
website
overridden in model class.
p.s. use read_attribute method read website
value in database.
Comments
Post a Comment