Reputation: 93
I have looked and looked, but I cannot find a method that will allow me to select a specific column based on a single condition (that does not involve a string query). The condition is arbitrary, but the column name is always the same. Below is my most recent (and desperate) attempt to better illustrate what I am trying to do.
@notExists = Company.select("name").where("name = ?", :company)
Ok, the query was correct, I was forgetting to use the '=>' in the below code. However, that now yeilds an error because :company is evaluating to be 'company'. According to the list of params in the server output window, its value is 'sample'.
Edit: full content
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
# Setup accessible (or protected) attributes
attr_accessible :email, :password, :password_confirmation, :remember_me, :company
validates :company, :presence => true
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :timeoutable
after_save :correspond
def correspond
@notExists = Company.select("name").where("name = ?", :company)
if @notExists.empty?
c = Company.new(:name => :company)
c.save
end
end
end
To see the full solution to this issue, please see dmarkow's answer below. One change was necessary to make it tick:
def correspond
c = Company.find_or_create_by_name(self.company)
end
Upvotes: 0
Views: 96
Reputation: 124419
The only thing that is preventing your code from working is that you're trying to use :company
which translates as a string instead of a variable.
Edit:
Your correspond method should be defined with a parameter and the first line of the method should use that parameter like so:
def correspond(user)
@notExists = Company.select("name").where("name = ?", user.company)
However, this is a much cleaner way of doing this -- it will only create the company if it doesn't exist:
def correspond(user)
c = Company.find_or_create_by_name(user.company)
end
Upvotes: 2
Reputation: 109
@notExists = Company.select("name").where("name = ?", :company)
will return []
if no matching records exist
@notExists = Company.select("name").where("name = ?", :company).first
will return nil
if no matching records exist
so if you are relying on it to be nil
if the record does not exist you need the second one.
you could test the first one with @notExists.empty?
Upvotes: 0
Reputation: 20000
The query you have seems fine. If you want to get just the column value, you could do:
company = Company.select("name").where("name = ?", :company).first
value = company && company.name
Upvotes: 0