Rails: How do I check if a column has a value?
This is what you asked for:
<% for agent in @broker.agents %>
<% unless agent.cell.blank? %>
<span class="cell-number">Cell: <%= agent.cell %></span>
<% end %>
<% end %>
The cell? method works whether cell is nil or an empty string. Rails adds similar functions for all ActiveRecord attributes. This will look a little nicer:
<% for agent in @broker.agents %>
<span class="cell-number">
Cell: <%= agent.cell? ? "none given" : agent.cell %>
</span>
<% end %>
The question mark and colon form a quick "if ? then : else" statement. There are two question marks in the code above because one is part of the method name cell? and the other is a part of the if/then/else construction.
Check whether a table column has any value
Try this in controller
@fabrics = Shirt.uniq.pluck(:fabric).reject { |f| f.nil? || f.empty? }
Rails: find if a value exists inside a array column
Discount.where(":user_id = ANY(user_id)", user_id: current_user.id)
This should do it for you. I assume that user_id
is an array field in a postgres database.
I'd recommend that you also index user_id
to be more performant. To create an index for your array column, you must choose between GiST and GIN as strategies. The documentation covers the options nicely, but the distilled version is that GIN lookups are much (3x) faster, but take longer (10x) to build. If your data is read far more often than it is written, go for GIN.
Your migration could be something like:
create_table "discounts", force: :cascade do |t|
t.string "amount"
t.string "name"
t.string "from"
t.string "to"
t.integer "user_id", default: [], array: true
end
add_index :discounts, :user_id, using: 'gin'
How to check if a column is present in a table?
You can use has_attribute?
:
user = User.new
user.has_attribute?(params[:group])
How to check if a model has a certain column/attribute?
For a class
Use Class.column_names.include? attr_name
where attr_name
is the string name of your attribute.
In this case: Number.column_names.include? 'one'
For an instance
Use record.has_attribute?(:attr_name)
or record.has_attribute?('attr_name')
(Rails 3.2+) or record.attributes.has_key? attr_name
.
In this case: number.has_attribute?(:one)
or number.has_attribute?('one')
or number.attributes.has_key? 'one'
Rails 4 detect if all the values in a column are the same
You can use uniq
and pluck
to do that:
puts Person.uniq.pluck(:birth_date).count == 1
You can also use select
method
puts Person.select('DISTINCT birth_date').count == 1
How to check if all records of an instance have one of many values from a list of values?
Your question title does not match the description. You're not checking whether "all records have the same value", you're checking that all records have one of many values (from a list).
There are a few issues with your attempt:
self.order.items.each do |item|
if item.state = "order_accepted" or item.state = "order_refused"
# ...
- Redundant use of
self
- Use of
=
is setting the value, rather than checking for equality. (This would be done with==
.) - By looping through all
items
like that, you're updating theorder
multiple times. - ...And since you're performing the check for each
item
, rather than all items, you're not checking that they all have the desired value.
A minimal change to your attempt that would work is:
if order.items.all? { |item| item.state == "order_accepted" || item.state == "order_refused" }
order.update_attributes(treated: "true")
end
However, that's not a great solution since you're loading all objects into memory and looping through them. This is inefficient, especially if there are lots of items
. A better approach is to perform the check directly in SQL
rather than in ruby
:
if order.items.where.not(state: ["order_accepted", "order_refused"]).empty?
order.update_attribute(:treated, "true")
end
To tidy this code up a little, I would define that query as a scope on the Item
model, such as:
class Item < ApplicationRecord
scope :not_completed, -> { where.not(state: ["order_accepted", "order_refused"]) }
end
And then perhaps define a method on the Order
model too:
class Order < ApplicationRecord
def complete?
items.not_completed.empty?
end
end
Then in the code above, you can just write:
def treatment
# ...
order.update_attribute(:treated, "true") if order.complete?
# ...
end
Also, I suspect that should really be true
rather than "true"
. true
is a boolean; "true"
is a string. Use the correct data type for the job.
Rails may be automatically casting the value to a boolean on your behalf (?), but I would consider it bad practice to use the wrong data type, regardless.
Ruby on Rails, find if a certain value exists in a column
Try this:
if User.exists?(:email => params[:user][:email])
flash.now[:error] = "A user with this password already exists"
render :action => :new, :layout => 'signin-layout.html.erb'
...
else
# more code here..
end
Also, you can add validations when you're creating the object:
class User
validates_uniqueness_of :email
More on different validations here: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
Checking if a tablecolumn contains a certain value
Maybe something like this:
<% if @user.games.rounds.submitted_pictures.where(:isFinalPicture => true).any? %>
How do I check to see if a column that stores an array 'includes' a parameter passed in to a 'where'?
If you are talking about Postgresql array column, take a look at this blog post which nicely summarizes using this type of column under rails.
You should be able to find records with any matching refactor_rule
with the following syntax:
Question.where("? = ANY (refactor_rules)", params[:rule])
See the ANY
operator for more docs.
Related Topics
Irb: How to Start an Interactive Ruby Session with Pre-Loaded Classes
Upgrading to Ruby 2.1.3 on MAC Osx 10.9.5
How to Find All Modules and Classes Within a Module, Recursively
Understanding Precedence of Assignment and Logical Operator in Ruby
Rails/Activerecord: Save Changes to a Model's Associated Collections
Sign Out Specific User with Devise in Rails
Ruby Convert Idn Domain from Punycode to Unicode
Extending a Class Method in a Module
Serialize Ruby Object to JSON and Back
How to Create a Charge and a Customer in Stripe (Rails)
Updated to Osx 10.9, Now Getting Ruby Error Using Homebrew
Installing Libyaml for Ruby on a MAC Osx (Lion)
Ruby on Rails: Search Form - Multiple Search Fields
Finding the Product of a Variable Number of Ruby Arrays
How to Tell Which Openssl Lib Is Actually Being Used by an Rvm-Installed Ruby