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
The only thing that is preventing your code from working is that you’re trying to use
:companywhich 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:
However, this is a much cleaner way of doing this — it will only create the company if it doesn’t exist: