1

I would like to add some text to a model when the json object is returned. For example

format.json { render :json => @user.to_json, :status => 200 }

The @user model contains a field called website. The user websites are in the format www.mysite.com, but I want the resulting json to display http://www.mymysite.com.

For example, there could be thousands of users.

@users = User.all  
format.json { render :json => @users.to_json, :status => 200 }  

I don't want to go through all the users and update the website column one by one. Is there a way to define this in the model where the returned value of website is http:// + self.website?

The more I research this it looks like I would override the method def as_json(options = {}), but I'm not sure how to do it to modify the website field.

1 Answer 1

1

You can have a method like the following in your User model class (app/model/user.rb):

def website_with_protocol
  "http://#{self.website}"
end

Then, you will be able to do: @user.website_with_protocol to get the user's website with http:// in the beginning.

Or, if you don't mind, you can override the website column in your database by defining a website method in the model class like this:

def website
  "http://#{self.read_attribute(:website)}"
end

So, now if you call: @user.website, then it will give you something like this: http://www.mymysite.com as the website is overridden in the model class.

P.S. Use the read_attribute method to read the website value in database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.