jamiri / proto

1 stars 1 forks source link

Two approaches to create and send JSON response #1

Open hsamadi opened 12 years ago

hsamadi commented 12 years ago

There are two approaches to create and send JSON response:

  1. The first is to retrieve the requested objects from database
@rows = Question.where(:lesson_id => @lesson_id)

and create the JSON response manually

  rows.each do |row|
    questions[row.id] = {
        "question" => row.question,
        "answer" =>  row.answer,
        "user_name" => row.user.name,
        "user_id" => row.user_id,
        "answered_by" => row.answered_by,
    }
  end

  questions.to_json
  1. Another approach is to retrieve the requested objects from database and use facilities provided by ActiveRecord to create JSON response
rows.to_json(:only => [:id, :question, :answer, :answered_by], :include => :user)

Which approaches do you think is better and why?

jamiri commented 12 years ago

Having surveyed some posts on Stack Overflow I noticed that most people follow Rails convention i.e. they use "to_json" method provided by ActiveRecord. By sticking to standards we can vaccinate our code against unseen problems :). So, I vote for ActiveRecord's to_json.

meqdadh commented 12 years ago

Second approach is the best choice.

hsamadi commented 12 years ago

@meqdadh But you were believing that the second approach may lead to more complex code! Something like this:

microblogs.to_json(:only => [:id, :title, :content], :methods => :posted_on, :include => 
  {:comments => {:include => :user}})

@meqdadh was also thinking that the first approach generates less text. So it would be more efficient. But I think being concerned with this issue is a kind of premature optimization.