K
K
Kirill Kazakov2015-12-15 14:50:12
Ruby on Rails
Kirill Kazakov, 2015-12-15 14:50:12

How to work with the result of a query from RoR to the database?

There is a model in RoR. I make a request to the database, a boolean value should be returned from the request.

logger.debug "subscribe_on subs-: #{subs}"
- shows
subscribe_on subs-: #Subscription:0x7f9954e08158

logger.debug "subscribe_on subs-: #{subs.inspect}"
shows
subscribe_on subs-: #Subscription subscribe: false

What type of data does the query return and how to get the boolean type from it?
Update:
Model :
validates :email, :presence=> true, 
  					:format=> VALID_EMAIL_REGEX,
  					:uniqueness=> {:if=> :subscribe_on?}
def subscribe_on?
  subs = Subscription.find(:email self.email).subscribe
  logger.debug "subscribe_on subs-: #{subs}"
end

UPD2:
In general, almost such code is needed
class Subscription < ActiveRecord::Base
  before_save { self.email = email.downcase}
  VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
  validates :email, :presence=> true, :format=> VALID_EMAIL_REGEX, :uniqueness=> {:scope => :subscribe}

Executing a query like this
SELECT 1 FROM `subscriptions` WHERE `subscriptions`.`subscribe` = 0 AND (`subscriptions`.`email` = BINARY '[email protected]') LIMIT 1

And instead of subscribe` = 0
subscribe` = 1
It didn’t work yet ( , how?
ruby ​​1.8.7

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dima, 2015-12-15
@mausspb

class Subscription < ActiveRecord::Base
  before_save { email = email.downcase}
  VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
  validates :email, :presence=> true, :format=> VALID_EMAIL_REGEX, :uniqueness=> {:if=> :subscribe_on?}
  
  scope :subscribe_on, lambda(subscribe_email){ where(email: subscribe_email, subscribe: true) }
        
  def subscribe_on?
    subs = self.class.subscribe_on(email)
    logger.debug "subscribe_on subs-: #{subs}"
    subs.first
  end
end

E
Eugene Burmakin, 2015-12-15
@Freika

If you have a Subscription model with a boolean subscribe attribute, then you need to request subs.subscribe. This should return true or false.

A
Artem Pyankov, 2015-12-15
@ibub1ik

It was worth putting the request itself into the body of the question, otherwise it is not very clear. From the comments, I understood that you are building a query through a model, so an instance (s) of this model will be returned. Moreover, if you specify the attributes that the query should return through select, then only they will be in the model.
Let's say you have a Foo model with bar and baz attributes.

f = Foo.select(:bar).first
# выведет bar
f.bar
# будет ошибка, т.к. этот атрибут не был загружен
f.baz

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question