0

I have a method (find_by_sql) that outputs a ruby object inside an array like this:

[#<deal id: 66480, opportunity_id: 4, admin_user_id: 1, created_at: "2015-09-20 18:37:29", updated_at: "2015-09-20 18:37:29", deal_available: true>]

How can I update the object's 'deal_available' attribute inside my database in raw postgresql ?

I tried different ways to write it but I stumble on the fact that it's very specific: it's an array, and inside there is a ruby object and I must manage to tell postgresql to change the value of deal_available: true to deal_available: false.

In local, I tried: logger.debug "Here is the resulting object for update:

 #{@deal_question[0]}

but I get:

#<@deal_question:0x007fd9b3963270>

Here is how @deal_question is created

@deal_question = Deal.find_by_sql(
      " SELECT \"deals\".*
        FROM \"deals\"
        WHERE (opportunity_id = #{@deal.id}
        AND deal_available = true)
        ORDER BY \"deals\".\"id\" ASC LIMIT 1"
    ) 

I don't even have a postgresql query to suggest here because first I need to understand how to query this ruby object inside the array.

1
  • 2
    Why don't you use ActiveRecord instead of writing raw SQL ? Commented Oct 13, 2015 at 16:14

1 Answer 1

1

You actually don't need a raw SQL query to update the deal_available attribute of your @deal_question object.

You can use update_attributes to achieve that.

# assuming @deal_question is an array
@deal_question[0].update_attributes(deal_available: false)

If you really want to use raw sql to update the attribute, then do this way:

array = [#<deal id: 66480, opportunity_id: 4, admin_user_id: 1, created_at: "2015-09-20 18:37:29", updated_at: "2015-09-20 18:37:29", deal_available: true>]
# grab the object to be updated
@deal_question = array[0]
# build the sql query string
sql = "UPDATE deals SET deal_available = false WHERE opportunity_id = #{@deal_question.id}"
# execute the sql to update the object
ActiveRecord::Base.connection.execute(sql)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, first suggestion did not work because it's only updating the objetc@deal question while I want to update the database. your second suggestion works. thanks!

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.