Ruby/Rails Collection to Collection
l = Library.find(:all, :include => :books)
l.books.map { |b| b.library_ids }.flatten.uniq
Note that map(&:library_ids)
is slower than map { |b| b.library_ids }
in Ruby 1.8.6, and faster in 1.9.0.
I should also mention that if you used :joins
instead of include
there, it would find the library and related books all in the same query speeding up the database time. :joins
will only work however if a library has books.
Rails activerecord get collection of collection
You can use has many through to get rails to do the joins for you.
class User
has_many :events
has_many :advertisements, through: :events
end
user = User.first
user_ads = user.advertisements
If you don't want to do that though you can do
user = User.first
ads = Advertisement.joins(:event).where(events: { user_id: user.id })
How to collect a collection of objects that are contained in the current month
If you already have an assignment where to take the date
from, you can get the first and last day of that month:
assigment_date = assignment.date.to_date
Assignment.where(date: assignment_date.beginning_of_month..assignment_date.end_of_month)
ruby rails - getting a collection of objects from a collection of foreign keys
You have two options for preserving order. First - eager load users in original query. In this case
users = @results.map(&:user)
Second - reorder on ruby side
idx = User.find(@results.map(&:user_id)).index_by(&:id)
users = @result.map{|r| idx[r.use_id]}
Rails: Iterate over collection within a Model's Class Method
Reverse your logic and let the database do the work. If all of them have a number_val
of 999
then none of them have a number_val
that is not 999
and this is easily expressed:
def self.all_have_number_value_999
!where.not(:number_val => 999).exists?
end
That will be a single fairly efficient database query.
Since this is a class method and class methods are mixed into relations (scopes are pretty much specific types of class methods after all), you can call this method on a relation and things like:
Foo.where(id: [123, 456]).all_have_number_value_999?
should work as would Foo.all_have_number_value_999?
.
If you want to perform some arbitrary logic while iterating over the collection outside the database, then you could throw in an all
call to resolve the query before iterating:
def self.all_have_number_value_999?
all.each do |foo_object|
...
end
end
rails 5 collection select
class Document < ApplicationRecord
has_many :entries
end
class Entry < ApplicationRecord
belongs_to :document
end
In your view file like: new.html.erb
<%= f.select :document_id, Document.all.collect { |p| p.id }, include_blank: true %>
Multiple select in collection
app/models/your_model.rb:
class YourModel < ApplicationRecord
serialize :activity, Array # add this
# you can't use `inclusion:` validation because it is only for validating a single value
# so you'll do something like this, or if you want it to clean it a bit by defining a method instead, see here https://stackoverflow.com/questions/13579357/validates-array-elements-inclusion-using-inclusion-in-array
validate do
unless %w(Vente Location Syndic Gestion).include? activity
errors.add(:activity, "#{activity} n'est pas un mandat valide"
end
end
end
app/views/.../some_view.html.erb:
<%= f.input :activity,
required: true,
autofocus: true,
label: "Votre Activité",
collection: ["Vente", "Location", "Gestion", "Syndic"],
input_html: { multiple: true },
include_hidden: false
%>
I added
input_html: { multiple: true }
above so that theparams
will be an array of values instead of just a single valueI added that
include_hidden: false
above because without it you'll get something like["", "Location", "Syndic"]
which adds an empty string instead of just..
["Location", "Syndic"]
- more info here
app/controllers/some_controller.rb:
devise_parameter_sanitizer.permit(
:account_update,
keys: [
:password,
:password_confirmation,
:photo,
:address,
:cover,
activity: [] # change this from :activity
)
Tested working
Rails: Query to get collection associated with collection
You just want to get all associated PlaceOfUseAreas
objects in single query, right?
If so, Rails have pretty single line solution for it:
PlaceOfUseArea.joins(:water_wights).uniq
Read more about joins method if you want more information.
Related Topics
How to Refresh a Page with Turbolinks
Cannot Install Ruby Gems - Zlib Error
Cloning an Array with Its Content
Can You Create/Write/Append a String to a File in a Single Line in Ruby
How to Profile Rspec with Perftools and Bundler
Sort a List with Multiple Conditions Ruby on Rails
Understand "Current_User" Concept When Creating a Login Session in Ruby
Should Rbenv Be Installed System-Wide, or at a User Level
Single Custom Param Name in Routes for Nested Resources Rails 4.1
Using Rvm, But Can't Set Current Ruby Version (Ubuntu 11.10)
How to Join a Table and Count Records in Rails 3
How to Upload a Local File to a Carrierwave Model
Rails Installation Error :The 'Atomic' Native Gem Requires Installed Build Tools
Ruby on Rails Collection Select - How to Pre-Select the Right Value
Rvm Install 1.9.2 Fails When Running Autoconf