0

Hi I am trying to create a custom controller that return a method as json.

Here my controller

respond_to :json
  def rates
    @event = Event.find(params[:id])
    respond_with @event.avg_rating
  end

Now I have my model with the following method

# returns the average rating for that event
def avg_rating
  @avg = self.ratings.average(:stars)     
  @avg ? @avg : 0
end

However when i get the respond I get this:

3.75

What I would like is a standard json respond either {"event": "3.75"}

But I am not sure what to use to simply transform it to make an answer like that

1 Answer 1

3

You will need an actual object to be rendered to json. A hash is usually easiest. And you will want to use render instead of respond_with

    render json: {:event => @event.avg_rating}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, simple and what i am looking for, will accept answer once allowed

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.