0

In my controller I have the present code that results in a JSON array, even though there is only one result:

def getSharedSpecial
    @result = Campaign.find_by_sql("SELECT 
                                     id
                                    ,name
                                    ,image
                                    ,ad_caption
                                    ,ad_details
                                    FROM campaigns 
                                    WHERE id = " + params[:shared_campagin_id].to_s + " 
                                    LIMIT 1;")

    respond_to do |format|
        format.html
        format.json { render json: { special_shared: @result }}
    end         
end

returns:

"special_shared":[
     {
"id":41,
"name":"tester the way",
"image":{
      "url":"/uploads/campaign/image/41/Gilded_pic.jpg"
        },
"ad_caption":"yfftitu6",
"ad_details":"jku"
      }
   ]
}

As can be seen given the [], this is a JSON array. How can I create just an object and not an entire array?

2
  • 1
    Could @result ever contain more than one result? If so, you should leave it as is. If no, then show us the code that creates the @results as it is what should be fixed. Commented Feb 6, 2015 at 0:54
  • ok, the code is SQL, added Commented Feb 6, 2015 at 1:05

1 Answer 1

1

The problem is that find_by_sql always returns an array even though you are only looking for a single record. There is no need to use find_by_sql and you've opened yourself to SQL injection attacks by doing so, so just write the finder the traditional way:

@result = Campaign.select(:id, :name, :image, :ad_caption, :ad_details).find(params[:shared_campagin_id])
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.