FAQ Database Discussion Community


rails query Virtual columns is not exits

ruby-on-rails,activerecord
I have write down this query in rails 4 result = User.select("id, (3959 * acos( cos( radians("+latitude+") ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians("+longitude+") ) + sin( radians(" +latitude +") ) * sin( radians( latitude ) ) ) ) as distants") when I...

Rails 4 - Create record with has_many through

ruby-on-rails,activerecord
In my project i have something like this: class User < ActiveRecord::Base has_many :roles has_many :websites, through: :roles end class Website < ActiveRecord::Base validates :name, presence: true has_many :roles has_many :users, through: :roles end class Role < ActiveRecord::Base validates :name, presence: true belongs_to :user belongs_to :website end So when I...

Rails: ActiveRecord::RecordNotFound in Cart

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
I user friendly_id for all the items. I am getting an error in the cart.rb model saying .. Couldn't find Product with 'id'=the-pen I'm unsure what to do. Any help would be appreciated cart.rb class CartItem < ActiveRecord::Base attr_reader :product_id, :quantity def initialize product_id, quantity = 1 @product_id = product_id...

in ActiveRecord::Relation, is it preferable to scope by parent in the model or set @parent in the controller

ruby-on-rails-4,activerecord,model-view-controller,scope,parent-child
I have a class which belongs to another. course.rb class Course < ActiveRecord::Base belongs_to :school I currently use a before_action to set the parent instance in the controller. courses_controller.rb class CoursesController < ApplicationController #returns @school. only: [methods] avoids trying to set @school when no school param expected before_action :set_school, only:...

Convert MySQL command to ActiveRecord

ruby-on-rails,activerecord
The command is SELECT * FROM txactions WHERE acccount_id = 1565 AND recon_status = 2 AND date_posted BETWEEN <var date1> and <var date2> ORDER BY date_poste LIMIT 1 ...

Equivalent for SQL WITH RECURSIVE in Arel

sql,ruby,activerecord,arel
I have the following SQL which recursively gets all of the parents of a record using WITH RECURSIVE. What would the equivalent of this be in Arel? table_name = self.class.table_name arel_table = self.class.arel_table sql = <<-SQL WITH RECURSIVE a AS ( SELECT * FROM #{table_name} WHERE id = '#{id}' UNION...

Rails joining multiple methods and scopes

ruby-on-rails-4,activerecord
My rails app provides a list of services which are defined like this: service.rb has_and_belongs_to_many :clients has_many :translations, class_name: ServiceTranslation, dependent: :destroy def with_translation(lang) includes(:translations) .where("service_translations.language_id=?", lang.id) .references(:service_translations) end scope :with_clients, -> { select("services.*, count(clients_services.service_id) as clients_count") .joins(:clients).group('services.id').order('clients_count desc') } So the with_translation method is eager...

activerecord query for a an array of arrays

ruby-on-rails,activerecord
I have the following models: Notification belongs_to :receiver, class_name: 'User' # has a sent_email boolean column default set to false User has_many :received_notifications, class_name: 'Notification', foreign_key: 'receiver_id', inverse_of: :receiver has_one :alert Alert belongs_to :user # has a frequency integer column I want to grab all the notifications where the sent_email...

ActiveRecord Survey Model ActiveRecord Associations for Doctor -> Patient

ruby-on-rails,activerecord,associations
I'm trying to build a survey form so that a User can select a Survey template, and then a form will be rendered with questions specific to that template. class Survey < ActiveRecord::Base belongs_to :template belongs_to :patient has_many :questions, :through=> :template has_many :answers, :through=> :questions end class Template < ActiveRecord::Base...

Rails, Postgres, ActiveRecord query postgres based on columns value

ruby-on-rails,ruby,postgresql,activerecord,postgresql-9.3
I working with Rails and Postgresql and I'm trying to query my postgres db based on the value of a column. To put it into perspective, I have an Events table in postgres and in that table I have some events that are recurring and some that aren't based on...

How to convert RIGHT LEFT functions to codeigniter active record

mysql,sql,codeigniter,activerecord
I have a query like this: SELECT RIGHT(id, 1) id_root FROM user WHERE LENGTH(id) = 3 and LEFT(id, 1) = '0' And how to convert that's query to active record in codeigniter. My problem is with syntax RIGHT( id, 1 ) and also at LEFT(id,1)='0'...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

No such column when creating an alias for a model association in Rails

ruby-on-rails,activerecord,associations,has-many
I want to create a one to many association between a User and Task model. In my user model I'd like to give it the alias of owner and refer to the user's tasks as owned_tasks. class User < ActiveRecord::Base has_many :owned_tasks, class_name: "Task", as: :owner end class Task <...

Rails 4 - Best way to perform an advanced search

mysql,ruby-on-rails,ruby,activerecord
In a custom advanced search form, what is the best way to perform a query to filter results? class UsersController < ApplicationController def index @users = User.all end end In many case we have different types of data, for example: name will be a string, surname will be a string,...

Complex many-to-many relation in Rails

ruby-on-rails,activerecord,has-and-belongs-to-many
I have a model Place. For instance, place can be a city, a district, a region, or a country, but I think one model will be enough, because there is no big difference between city and region for my purposes. And places can belong to each other, e.g. a region...

Store accessor for nested JSON

ruby-on-rails,json,activerecord,jsonb
I have the model "Organization" that stores all information related to an organization. There is a field of type JSONB named "integrations" that stores information pertaining to all external service integrations that an organization has. How do I use store accessors to access information stored in nested JSON, for example...

Rails: select model

sql,ruby-on-rails,activerecord,associations
I have a model Shop: class Shop < ActiveRecord::Base has_and_belongs_to_many :services end and a model Service: class Service < ActiveRecord::Base has_and_belongs_to_many :shops end I would like to query every shop that provides all of the following services: Reparation Advise Shipping So return all shops where services contain reparation AND advise...

ActiveModel::Dirty watch only specific fields

ruby-on-rails,activerecord
I'm not 100% sure about why ActiveModel::Dirty has its name. I'm guessing it is because it is considered as dirty to use it. But in some cases, it is not possible to avoid watching on specific fields. Ex: if self.name_changed? self.slug = self.name.parameterize end Without ActiveModel::Dirty, the code would look...

Get has_many from ActiveRecord::Relaiton

ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord
Is it possible to get the has_many records from an ActiveRecord::Relation? i.e. Book.where(fiction: true).pages as opposed to Book.where(fiction: true).collect { |book| book.pages } Ideally I'd like to be able to get all the records using one ActiveRecord query, so I don't have to build up the array in memory, and...

Rails find_or_create_by with/without where

ruby-on-rails,ruby,activerecord
Let's say I have a model named Task. And I want to find_or_create_by some task. t = Task.where(done: false).find_or_create_by(title: 'epic') This model works, but create a task with title equal to epic and done equal to false. I want query search through done equal to false, but I don't want...

DB issue in rails? Rails query and SQL query return different results (default_scope's fault?)

ruby-on-rails,postgresql,ruby-on-rails-4,activerecord,devise
We have over 29K users in our database. "User" is one of our tables and has a unique field "email" with an index defined in one of our migrations: #3434324_devise_create_user.rb class DeviseCreateUsers < ActiveRecord::Migration def change create_table(:users) do |t| t.string :email, :null => false, :default => "" end add_index :users,...

Rails: Posting from a form to a M:M table

ruby-on-rails,activerecord
On the group index page I display a listing of group discussions and a form to create a new discussion. class Group < ActiveRecord::Base has_many :discussions end class Discussion < ActiveRecord::Base belongs_to :user belongs_to :group end Controller: class DiscussionsController < ApplicationController def index @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build({group_id: @group.id})...

Building a simple calculator form in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,strong-parameters
I am looking to build a simple set of calculators in a Rails 4 application and I am at a bit of a loss as to how I should go about setting up my models and controllers. In this example I have a series of calculators that will have very...

Ruby on Rails 4 count distinct with inner join

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
I have created a validation rule to limit the number of records a member can create. class Engine < ActiveRecord::Base validates :engine_code, presence: true belongs_to :group delegate :member, to: :group validate :engines_within_limit, on: :create def engines_within_limit if self.member.engines(:reload).distinct.count(:engine_code) >= self.member.engine_limit errors.add(:engine, "Exceeded engine limit") end end end The above doesn't...

Combine logic of boolean value & integer in one activerecord model

ruby-on-rails,ruby,activerecord
Let say I have a model named a Product. Product has a days_lifetime:integer in days (it can expire in 1, 2, 3 et.c. days after initialization). But sometimes Product has unlimited lifetime (it can be stored infinitively long time). So, I need to add another variable like unlimited_lifetime:boolean Now I...

ActiveRecord - illegal mix of collations

mysql,ruby-on-rails,ruby,activerecord,character-encoding
I am having some issue with Ruby's ActiveRecord with the Redmine application. Started PATCH "//issues/33135" for [ipaddress] at 2015-06-02 17:02:48 -0700 Processing by IssuesController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"[secret_token]", "issue"=>{"is_private"=>"0", "project_id"=>"949", "tracker_id"=>"4", "subject"=>"adgsasdg", "description"=>"asdggsad", "status_id"=>"1", "priority_id"=>"1", "assigned_to_id"=>"", "parent_issue_id"=>"", "start_date"=>"2015-06-02",...

How do I create a performant scope based on the virtual attributes of an associated model?

ruby-on-rails,ruby-on-rails-4,activerecord
I have a Node model. Each node object has a virtual attribute called user_tags or user_tag_list which was inherited from acts_as_taggable. It looks like this: [24] pry(main)> n => #<Node id: 85, name: "House Fire 2", family_tree_id: 57, user_id: 57, media_id: 228, media_type: "Video", created_at: "2015-05-15 00:20:26", updated_at: "2015-05-20 01:06:34",...

Trouble in RSpec test - saving parent record twice

ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes
I'm new at Rails programming, and my RSpec test is failing when trying to save nested records. The logs from the test suggest that ActiveRecord is trying to save the parent twice, which results in a silent database save failure. sign_up_spec.rb (sorry for the omission!) require 'rails_helper' RSpec.feature "Accounts", type:...

has_and_belongs_to_many loads wrong resource

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
I have 3 models # generic one class Someone < ActiveRecord::Base end # customer class Customer < Someone has_and_belongs_to_many :groups, join_table: "some_join_table", class_name: "Group" end # custom group class Group < GenericGroup has_and_belongs_to_many :customers, join_table: 'some_join_table', class_name: "Customer" end Let's assume that database is feeded. When i execute command Customer.first.groups...

Rails query through association limited to unique associated objects?

sql,ruby-on-rails-4,activerecord
class User has_many :books I need a query that returns: Three most recent books belonging to unique users. I.e. if my DB has users: id: 1, name: "John" id: 2, name: "Mary" id: 3, name: "Bob" books: id: 1, title: "Ender's Game", user_id: 1 id: 2, title: "Dune", user_id: 1...

rails block a record for change for another places in the code

ruby-on-rails,ruby,postgresql,activerecord,sidekiq
I have a ruby on rails application with a lot of sidekiq workers. Some of workers can work for a while (at least few minutes). How can I block some record for changes from another places (ie controllers), to avoid data conflict when I save this record in the worker?...

How do I get several attributes value and method value from an ActiveRecord model?

ruby-on-rails,ruby,activerecord
To solve my problem, I set fictitious Car Model below: Car Model has 3 attributes(id, car_name, owner_name) and 2 methods which return integers(riders, passengers). I want to get ONE HASH which has the values of 2 attributes and 2 methods from all of cars. To solve this problem, my temporary...

Easy way to search values with dash (-) and space seperated in SQL

sql,ruby-on-rails,postgresql,activerecord
Hi i have many record in my db as - above the line... - above-the line... - above-the-line... - above the-line... I want to query them with like query Select words.* from words where sentence ILIKE 'above the line%'; But this query naturaly gets only first result. Is there a...

How do you retrieve k prior posts before an id in ActiveRecord

ruby-on-rails,activerecord
I am trying to do infinite scrolling in reverse where I show the most recent 20 posts initially. As the user scrolls up, I want to retrieve (in Rails) the next 20 recent posts, etc... The following code almost does it, but it gives the list of posts in reverse...

how to assign Post to User through user_id and author_id?

ruby-on-rails,activerecord,relationship
I have a table users. they can post records in different users profiles, so for every post I have user_id (in whose profile a post was written) and autor_id (who wrote the post). Please could you help me - which relations should be to connect posts model with users twice?...

Ruby destroy is not working? Or objects still present?

ruby-on-rails,ruby,activerecord,destroy
A plan has many plan_dates. This is a trivial example from my console a = Plan.create a.plan_dates.create( ddate: Date.today) a.plan_dates.create( ddate: Date.today + 1.days ) a.plan_dates.create( ddate: Date.today + 2.days ) a.plan_dates.count # => 3 a.plan_dates.each { |pd| puts pd.ddate } # => 2015-06-06 00:00:00 UTC # => 2015-06-07 00:00:00...

Order By count(*) from other table in yii 2

php,mysql,activerecord,order,yii2
I have 2 table: videos and likes video table has fields: id, title .. likes table has fields: id, video_id, user_id I would like to get the 10 most like videos. I can do it in sql by command: SELECT videos.*, COUNT( likes.video_id ) AS countlike FROM videos LEFT JOIN...

activerecord relations rails confusion

ruby-on-rails,ruby,activerecord
I want to create a database for drinks. Each drink has many ingredients, and ingredients have many doses. So, a ingredient belongs to a dose and a dose belongs to cocktail. But once I delete a drink I want to remove the associated doses but not the ingredient because that...

rails has_many at least one children has the value

sql,ruby-on-rails,ruby,ruby-on-rails-4,activerecord
Let say I have a Group of Users and User has a enum, which described it's mood. class Group < AR::Base has_many :users class User < AR::Base belongs_to :group enum mood: %i(good bad ugly) How can I find all groups, where at least one User has the good mood? Which...

Rails Trying to create a profile after the user has been created

ruby-on-rails,ruby-on-rails-4,activerecord,devise
I'm trying to figure out how to create a new profile for the user that has just been created, I'm using devise on the User model, and the User model has a one to one relationship with the UserProfile model. Here's what my User Model looks like: class User <...

ActiveRecord - How to know if a field exists on another table?

ruby-on-rails,ruby,activerecord
I want to update the status in the winners table into trues if a user with same mail id is signed up. I'm stuck with active record. schema.rb create_table "winners", force: :cascade do |t| t.string "name" t.string "email" t.string "phonenumber" t.boolean "status", default: false t.datetime "created_at", null: false t.datetime "updated_at",...

How to validate non-db attributes on an ActiveRecord model?

ruby-on-rails,validation,activerecord
I have the following class: class Instance < ActiveRecord::Base attr_accessor :resolution validates_format_of :resolution, with: /\A\d+x{1}\d+\d/ def resolution=(res) validate! (set the resolution etc) end def resolution (get the resolution and return) end end The resolution attribute is not stored in the database, but is a transient property of the instance. When...

Rails find_by - Association comparison

ruby-on-rails,activerecord,associations
I've got three models: class User < ActiveRecord::Base has_many :surveys end class Survey < ActiveRecord::Base belongs_to :user has_many :survey_sessions end class SurveySession < ActiveRecord::Base belongs_to :survey end My question: If this is possible: Survey.find_by!(id: params[:id], user: current_user) Why does this throw a SQLException at me? SurveySession.joins(:survey) .find_by!(id: params[:id], surveys: {user:...

Search does not return any value in Rails 4

ruby-on-rails,ruby-on-rails-4,activerecord
My Controller: def index @three_data = Threeddatum.all @three_data = @three_data.search(params[:search]) if params[:search].present? end My model: def self.search(search) if search self.where("area LIKE ?", "%#{:search}%") else self.all end end My view: <%= form_tag('/threeddata', method: :get) do %> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", name: nil %> <% end %> <%...

Activerecord migration error on postgresql

ruby-on-rails,postgresql,activerecord
I have a error without explanation. My error : G::UndefinedColumn: ERROR: column "conjoncture_index_id" referenced in foreign key constraint does not exist : ALTER TABLE "reports" ADD CONSTRAINT "fk_rails_c25ad9a112" FOREIGN KEY ("conjoncture_index_id") REFERENCES "conjoncture_indices" ("id") My migration : class AddColumnToReports < ActiveRecord::Migration def change add_reference :reports, :conjoncture_indice, index: true add_foreign_key :reports,...

undefined method `location' for #

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
I have two models: Event and Location. Location has_many events and an event belongs_to a location. A location has an attribute called "city". In a controller, I have the following code: @locations = Location.all.includes(:events) @events = @locations.collect{|l| l.events} @events.each do |event| puts "event is #{event.inspect}" puts "event location is #{event.location}"...

Rails 4 many-to-many associations nightmare

ruby-on-rails,ruby,activerecord,many-to-many,associations
I'm trying to set up a has_many :through association between three models: Trip, Location and LocationsTrip, but the associations just don't seem to be picking each other up. I set up my associations: class Trip < ActiveRecord::Base belongs_to :user has_many :locations_trips has_many :locations, :through => :locations_trips accepts_nested_attributes_for :locations_trips, :allow_destroy =>...

Finding non-eager loaded relations used in a Rails view

ruby-on-rails,ruby,activerecord
So, I've inherited a medium sized legacy app that was quickly built to address a customer's need. Luckily it was well written for the most part but because it was rushed there are a lot of places that ActiveRecord relations were not eager loaded. As the traffic of the site...

Rails create column with a day of week and two date times

ruby-on-rails,ruby-on-rails-4,activerecord
Currently I am building a homepage for my local soccer club and I want to save training times for each team. The training times will look something like this: Tuesday 18:00-19:30 Thursday 18:30-20:00 What is the best way to store these values inside the database in rails?...

Rails 4 – How to rescue from NoMethodError and continue trying method?

ruby-on-rails,ruby,activerecord,rescue
In my Contacts class, after a contact is created with their email address, I try to pull as much contact data from FullContact's API as possible. I'm having this issue where if one column of data doesn't exist for a "person" in FullContact, it throws a NoMethodError and I don't...

Count from associate table

ruby-on-rails,activerecord,count
I want to have some stats from my app, User can publish post that I call Idee, and I want to know how many user have publish at least one idee. I'm assuming that should be something like: @total_user_active = User.where(idee.size >= 1).count But this doesn't work. It's user who...

How to escape the ? (question mark) operator to query Postgresql JSONB type in Rails

ruby-on-rails,postgresql,activerecord,jsonb
I'm working with Rails 4.2 and Postgres 9.4 to try out the new JSONB data type. One of the JSONB columns in my database holds an array, and I want to be able to query for records where this array contains a certain value. I figured out how to do...

Ruby ActiveRecord: How to connect two rooms with an exit

ruby,activerecord,orm,rails-activerecord,adventure
I am making a small text-adventure, and I want to use ActiveRecord as Object Relational Mapping. What I'm having trouble with, is understanding how to connect two rooms together using an exit. The following facts are a given: A room can have multiple exits An exit can be in different...

Rails Active Record find every 10th record

sql,ruby-on-rails,activerecord
I'm looking for a way to find every 10th record in my 'Lang' database starting with the first record. Something like this: @words = Lang.find(records with ids of 1,11,21,31,41...) ...

“NameError: uninitialized constant” on existing ID

ruby-on-rails,ruby,activerecord
I get this error when running rake db:seed in my app: NameError: uninitialized constant AdmissionEpisode::AdminDistrictId. I have no idea why - admission_episode.admin_district_id exists in the database and I have belongs_to :admin_district in the AdmissionEpisode model. Does anybody have any idea what's going on? Here is the AdminDistrict seed: districts.each do...

how to set new variable to activerecord object in rails

ruby-on-rails,ruby-on-rails-4,activerecord
Can I do this in Rails 4? book.new_variable= 4 Where book is an ActiveRecord object just fetched from the db. new_variable is not a column in books table. I was trying to do this but rails gives me error undefined method new_variable=. Is there any other way to set variable...

Group by class in Rails 4.0

ruby,ruby-on-rails-4,activerecord
I have Product model in my project. And it has product_type as a field. I want only one product from all types of products. I tried doing this, Product.group_by(:product_type).limit(1) This did not work. How can i achieve this?...

Repeating same block of code over an ActiveRecord Object's attributes in Ruby (Rails)

ruby-on-rails,ruby,activerecord
I have a basic function which takes in different values for weight and reps for a barbell lift, and converts it to an estimated one rep max, which gets stored in my database. Here is what the code currently looks like: if deadlift_reps != 1 self.deadlift = deadlift_wt * deadlift_reps...

Table Join in Rails Active Record

ruby-on-rails,ruby,activerecord
I have a film model class Film < ActiveRecord::Base has_many :film_genres has_many :genres, through: :film_genres end a genre model class Genre < ActiveRecord::Base has_many :film_genres has_many :films, through: :film_genres end and then I have my filmGenre model class FilmGenre < ActiveRecord::Base belongs_to :film belongs_to :genre end Im try to get...

ActiveRecord: How to find parents whose ALL children match a condition?

ruby-on-rails,postgresql,activerecord
Suppose I have a Parent model that has many Child, and that Child also belongs to OtherParent. How can i find all Parent where ALL of its Child belongs to any OtherParent? In pure SQL I could do Parent.find_by_sql(<<SQL) SELECT * FROM parents p WHERE NOT EXISTS ( SELECT *...

Rails ActiveRecord how do I find all records where the record is not joined with a particular other record?

ruby-on-rails,activerecord
I want to search for all users (Users) who are not part of group 1 (Groups), joined by UserGroups, i.e. "find all users that do not have a UserGroups record binding them to Group 1." I can find all users with User.all or find them by name with User.where('name like...

Trouble importing multiple CSVs as Rails while maintaining associations

ruby-on-rails,ruby,csv,activerecord
First post. Relatively new to Rails and coding in general. I'm having trouble importing seed data from multiple CSVs into Rails and ensuring that associations are maintained. Data are data on restaurants and inspections done on those restaurants (restaurants have_many inspections, and inspections belong_to restaurants) This problem appears similar to...

undefined method `loan_amount' for nil:NilClass

ruby-on-rails,ruby-on-rails-4,activerecord,foreign-keys,foreign-key-relationship
I am doing a jewel loan application using ruby 2.2.2p95 (2015-04-13 revision 50295) [i686-linux] and Rails 4.2.1 in that i am having two models: 1)jewelloan.rb 2)jltransaction.rb I have added foreign key jewelloan_id to get the loan_amount in jltransactions table. Where as loan_amount is a field in jewelloans table. My problem...

delayed_job_active_record - Undefined method `any?'

ruby-on-rails,activerecord,delayed-job
Attempting to send some stuff to the background with delayed_job_active_record, but how come I can't use any?? Works fine when things are not sent into the background. undefined method `any?' for #<Delayed::Backend::ActiveRecord::Job:0x000000044b1348> index.html.erb <% if @products.any? %> <div class="products"> <% @products.each do |product| %> <%= product.name %> <% end %>...

Need to store query result instead of storing query in ActiveRecord

ruby-on-rails,activerecord
I am having following function to find some of the selected records from public pages. def find_public_page(title) @footer_public_pages ||= PublicPage.where(title: %w(welcome_to_toylist terms_of_services buying_a_toy selling_a_toy requesting_a_toy ad_guildelines)) @footer_public_pages.find_by(title: title) end what I need is that @footer_public_pages should store the result set in first time and then on next time it will...

Rails: active record saving time:type with unwanted format

ruby-on-rails,ruby,activerecord,time
I have a table call periodo with the attribute hour. i pass my time param in this way hour = Time.parse( splitLine[1] ) #where splitLine[1] is my time but in string periodo = Periodo.new(:hour => hour.strftime("%H:%M")) periodo.save but active record save the records in this way hour: "2000-01-01 07:00:00" ,...

Complex rails SQL query

sql,ruby-on-rails,ruby,postgresql,activerecord
First of all, a user has many age_demographics. An AgeDemographic object looks like this: #<AgeDemographic id: 4384, user_id: 799, range: "35 - 49", percentage: 3.2, created_at: "2015-05-22 04:17:10", updated_at: "2015-05-22 04:17:10"> I'm building a user search tool where someone will select multiple age ranges that they want to target ("12...

rails find records containing specific word [duplicate]

ruby-on-rails,database,activerecord
This question already has an answer here: Rails: How to find_by a field containing a certain string 4 answers I'm looking for a way to find all entries in a database containing a specific string. I know it's possible to iterate over every entry and see if a string...

Having troubles with “all” method and getting “ArgumentError at”

ruby-on-rails,ruby,activerecord,padrino
I'm having troubles using the method "all" in this code: posts = Post.includes(:account).all(:conditions => condition, :order => "created_at DESC", :limit => postsPerPage, :offset => (page-1)*postsPerPage) When i start the server and go to the web page Padrino throws an error: ArgumentError at / wrong number of arguments (1 for 0)...

Chartkick gem, limit group in pie chart and multiple series

sql,ruby-on-rails,activerecord,charts,highcharts
I have small problem with grouped records. Chart code: <%= pie_chart CountChatLine.group(:channel).count %> The problem is, that I have more than few :channels in database, and chart looks like this: Can I somehow take only N top :channels and sum rest of it as others or something? Or add to...

Update/Delete wrong record because of ActiveRecord “type”

ruby-on-rails,ruby,activerecord
I have 2 tables Foo and FooArchive, where FooArchive is a replica of Foo. FooArchive is for storing old data from Foo in order to optimize and keep the first from growing too big. class Foo < ActiveRecord::Base end class FooArchive < ActiveRecord::Base end Foo is subclassed: class OneFoo <...

Creating a status attribute for a model

ruby-on-rails,ruby,activerecord,model,attributes
I want to create a status attribute for my Taskmodel that would indicate where it is in a three part progress in this order: open => in-progress => complete. It would work in a way similar to how an Amazon package is delivered: ordered => shipped => delivered. I was...

How can I tell if an ActiveRecord object will be destroyed before it actually is?

ruby-on-rails,ruby,activerecord
Whenever I create, update, or destroy a model I need to send a notification to a front end app. When sending the message, I need to know if the record is a newly created record OR if the record has been deleted. To avoid duplication I'd prefer to handle all...

How do I associate an Activerecord Object with Em-Websocket connection?

ruby,activerecord,sinatra,em-websocket
I am new to ruby. I am trying to implement a chat client using em-websocket. I have the following code: EventMachine::WebSocket.start(host: '0.0.0.0', port: 8080) do |websock| websock.onopen do puts 'New Connection Opened' cookies = CGI::Cookie::parse( websock.request["cookie"]) person = Person.where(['token = ?', cookies["token"]]).first unless person websock.close(code = nil, body = {Error:...

How do I create a complex left outer join in Yii2?

php,activerecord,orm,yii2
How do I perform this query in Yii2? SELECT `keyword`.`id`, `keyword`, `volume`, `cpc`, `competition`, `keyword_id` FROM `keyword` LEFT JOIN `ad_group_keyword` ON keyword.id = ad_group_keyword.keyword_id and ad_group_id = 1 WHERE ((`keyword_id` IS NULL) AND (NOT (`volume` IS NULL))) AND (NOT (`cpc` IS NULL)) ORDER BY volume desc LIMIT 1; I tried...

Codeigniter: Loop in start_transaction

php,codeigniter,activerecord,transactions
I'm using for loop in a transaction. I have a question about this loop. While it's inserting e.x 100 rows to database, among inserting, if another person wants to insert, does it make problem, or insert_id() won't change? Thanks. $this->db->trans_start(); $query = $this->db->query("INSERT INTO category (Cat_Name, Subname, IsActive, Description) VALUES(?,...

ActiveRecord query with OR and where.not

sql,ruby-on-rails,ruby,ruby-on-rails-4,activerecord
I have the following queries that work separately, but I haven't been able to make one query out of it, and I'm not sure what the SQL approach would be. Any recommendations? Discussion.joins(:discussion_tags).where.not(discussion_tags: { taggable_type: 'Product'}) Discussion.includes(:discussion_tags).where(discussion_tags: { id: nil}) ...

How do I add extra data to model before submit from form in Rails

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
I have a form that a user fills out that I need to add some extra 'behind the scenes' data to before creating the object in my DB. For instance, data like a referrer_url, clout_score etc. How do I go about doing it? Are the methods something that should sit...

Best practice for sharing translation of Active Record attributes

ruby-on-rails,activerecord,internationalization,yaml,rails-activerecord
I have the following yaml in one of my translation files: se: activerecord: attributes: user: name: "Namn" town: "Stad" admin: name: "Namn" level: "Nivå" pet: name: "Namn" company: name: "Namn" food: name: "Namn" Is there a way for me to DRY this up and share the translation of name across...

Aliasing calculation result, grouping, and summing in ActiveRecord query using Postgres

ruby-on-rails,postgresql,ruby-on-rails-4,activerecord
I'm trying to calculate the total value of each OrderItem by multiplying the unit_price by the quantity and subtracting the line_discount, and then grouping by the product_id and summing the line_total so I can get the total line totals for each product. I tried this first: OrderItem.select("order_items.*, order_items.unit_price * order_items.quantity...

Rails Active Record group or ignore duplicate results from query

mysql,ruby-on-rails,postgresql,activerecord,rails-activerecord
I have an active record query which returns a list of tags from search query. I'm rendering that to json to use in a tag search. The issue is that the query will return multiple tags of the same kind. Is there any ignore multiples or group multiples? Here's the...

Is there a standard way to get an ActiveRecord item within Ruby on Rails from a given URL?

ruby-on-rails,ruby,activerecord
Is there a standard way to get an ActiveRecord item in Ruby on Rails from a given URL? I have some data in an external RDF database which I can query to get URLs for items in my Ruby on Rails code. I then want to get hold of the...

Rails: Garble data as it leaves the database

mysql,ruby-on-rails,activerecord
Basically, I'm looking for a way to inject code before queries are executed against certain tables. For example, if I query against the users table (ignore the joins/or complex statement possibilities) I want to garble the output so that you can still get something back but it won't be readable....

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many
I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

No such column for attribute in a join table

ruby-on-rails,activerecord,attributes,associations,jointable
I'm trying to create an app where a user chooses volunteers to complete their task. The way that volunteers are considered participants is through the selected boolean attribute placed on the TaskVolunteer join table. Unfortunately when I try to find the participants of a particular class I get the following...

activerecord not like query

ruby-on-rails,activerecord
I could not find an activerecord equivalent of "Not Like". I was able to find a where.not, but that will check if a string does not match a value, as so: User.where.not(name: 'Gabe') is the same as: User.where('name != ?', 'Gabe') I was looking for a NOT LIKE, where the...

nested foreach in codeigniter view

php,mysql,codeigniter,activerecord,foreach
I have 4 tables: process, country, process_country and category. Each process belongs to a certain category. A country may have several processes available and a process may be available in several countries. Below is my database structure: category table process table country table process_country -------------- -------------- ------------- --------------- categoryid processid...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord
Each question has an array of tags. schema.rb: create_table "questions", force: true do |t| t.text "tags", default: [], array: true How to atomically append to tags? How to prevent dups within the array? I tried question.update_attribute tags: tags << :ruby, but this doesn't work. Rails 4.17 and Postgres. EDIT: This...

Query by two column version number in rails

ruby-on-rails,ruby,activerecord
I have two columns called major and minor that I am trying to do greater and less than queries on. They represent versions. So for version 2.1, the 2 is in the major column and 1 is the minor column. How can I do these queries? I would like to...

undefined method `includes' for object instance

ruby-on-rails,ruby,performance,ruby-on-rails-4,activerecord
I'm using Ruby 2.2.1 and Rails 4.2 to build an app. At one of my views, I got the following message: N+1 Query detected Politician => [:account] Add to your finder: :includes => [:account] N+1 Query method call stack app/models/user.rb:19:in `account' app/controllers/home_controller.rb:6:in `index' Here is my action at home controller:...

Multiple many-to-many association between two models

ruby-on-rails-4,activerecord,associations
I've created a many to many relation ship like the following structure. Class User has_many :companies, :through => company_admins has_many :company_admins end Class Company has_many :company_admins has_many :users, :through => company_admins end Class CompanyAdmin belongs_to :company belongs_to :user end Here, User can be assigned as admin on many Company. Now...

How to build object with many relationship

ruby-on-rails,ruby,activerecord
I have 3 models User, Course and Group. Their relationship is as follows user.rb has_and_belongs_to_many :courses belongs_to :group group.rb has_many :users belongs_to :course course.rb has_many :groups, dependent: :destroy has_and_belongs_to_many :users I want to create a new group. How can I build group object? My user and course objects are below...

Active Record Where Clause For Relation In Model

ruby-on-rails,activerecord
I have two Models User and Site. The User has category like 'basic and premium'. The user has relation to sites one -> many (i.e one user can have more than one sites). Now i want to select sites of premium user. Can someone tell me how to use where...

conditionally retrieve records in a has_many through extend method

ruby-on-rails,ruby,activerecord
I'm trying to figure out how to conditionally retrieve records in a has_many through association. I have three classes: class User < ActiveRecord::Base has_many :user_associations has_many :projects, source: :user_associatable, source_type: 'Project', through: :user_associations do def owned # retrieve projects that have is_owner = true on the user_association end end end...

PG::NotNullViolation: ERROR: null value but the value was set via ActiveRecords

ruby-on-rails,ruby,activerecord
I'm trying to create a new record in my Categories table using ActiveRecords Here is my ActiveRecords class: require_relative '../../database/contract' require 'active_record' class Category < ActiveRecord::Base self.table_name = Tables::CATEGORIES def initialize(name) @active = true @name = name super() end end And here is what I'm trying to do: category =...

(dynamic) Rails model (object) parameters (values) through has_many associations

ruby-on-rails,ruby,activerecord
I have a multiple models (ie. tires and rims). Multiple models have multiple parameters (like color, size, type, etc.) I have this: Parameter: belongs_to :tires belongs_to :rims ParameterValue: belongs_to :parameter belongs_to :tires, :through => :parameter belongs_to :rims, :through => :parameter Tire: has_many :parameters Rim: has_many :parameters Here goes the problem....

implement has_many through association in rails 4

ruby-on-rails-4,activerecord,has-many-through
I am working with has_many :through association in Application. I implement association between models like :- in employee.rb class Employee < ActiveRecord::Base has_many :inventories, through: :employee_inventories end in inventory.rb class Inventory < ActiveRecord::Base has_many :employees, through: :employee_inventories end in employee_inventories.rb class EmployeeInventory < ActiveRecord::Base belongs_to :employee belongs_to :inventory end I...

Redirect if ActiveRecord::RecordNotUnique error exists

ruby-on-rails,postgresql,activerecord,error-handling
I have the next code to save: Transaction.create(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now).save! But how can I redirect to main root page if this ActiveRecord::RecordNotUnique error appears? Can I catch this error?...

Is it possible to have two callbacks in around_destroy in rails?

ruby-on-rails,activerecord,callback
Although this can be accomplished as follows: class Model < ActiveRecord::Base around_destroy :callback def callback puts 'callback1 before yield' puts 'callback2 before yield' yield puts 'callback1 after yield' puts 'callback2 after yield' end end But I wish to do the following: class Model < ActiveRecord::Base around_destroy :callback1, :callback2 def callback1...

Updating attributes from check_box

ruby-on-rails,ruby,activerecord
I'm using nested models in my first Ruby on Rails app and now I've run into a problem. I have a Survey model that has_many :questions which in turn belongs_to :survey and the model Question has_many :answers. My Answer model then belongs_to :question. Now I want to update a boolean...