FAQ Database Discussion Community


undefined method find_all_by_full_profile_id for Class in linkedin gem

ruby-on-rails,ruby,rails-activerecord
I write app which will give all my data from LinkedIn. I did all but I have this error line: undefined method `find_all_by_full_profile_id' for #<Class:0x007f4779a08008> what this means and how can I fix it?...

Rails use a non-id column for model associations

ruby-on-rails,ruby-on-rails-4,rails-activerecord
How can I specify a column for a Rails model association to use as its foreign_key? This is "id" by default, and I would like to specify another column. Example: question.rb class Question < ActiveRecord::Base has_many :answers end answer.rb class Answer < ActiveRecord::Base belongs_to :question end Both the "questions" and...

Trouble setting up ActiveRecord many to many relationship

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
I'm having some difficulty in getting a many to many relationship working in my Rails app. I'm running Ruby 2.2.2p95 and Rails 4.2.0. NoMethodError: undefined method `each' for #<Topic id: 1> seeds.rb:63:in `<top (required)>' My video model: class Video < ActiveRecord::Base has_and_belongs_to_many :topic end The topic model: class Topic <...

How do I add a method to ActiveRecord::Batches?

ruby,rails-activerecord
I was trying to add my custom implementation for ActiveRecordss find_in_batches method. First, I tried to monkeypatch the corresponding module: module ActiveRecord module Batches def find_in_batches2 end end end Task.find_in_batches2 do |group| end But ruby said: NoMethodError: undefined method `find_in_batches2' for Task (call 'Task.connection' to establish a connection):Class /home/yuri/.gem/ruby/2.1.5/gems/activerecord-4.2.0/lib/active_record/dynamic_matchers.rb:26:in `method_missing'...

How do I having one model listen for updates of another?

ruby-on-rails,rails-activerecord
I have two models, Subscription and Offer. Subscriptions have many offers. Offers have one subscription. Subscriptions and offers also have statuses. If the subscription status changes, all associated offers must change with it (but not vice versa). Right now we're using an after_save hook to go through and update a...

How to properly escape a regular expression in Active Record where clause

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
I am using Active Record v4.2.1 to query a mySQL database using a regular expression. I would like to create the following SQL: SELECT `users`.* FROM `users` WHERE (email REGEXP '[@\.]gmail\.com') However, I cannot seem to find the correct way to create the SQL using Active Record. User.where("email REGEXP ?",...

How to clear memory cache in Ruby?

ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord
I'm new to Ruby. I've got a rails application and I'm keeping site configuration (like site name) in the database. I've set up a helper so I can call: site_param 'site_name'. The helper stores the data in a variable so that the application doesn't hit the database on each call,...

get multiple records in one query in ActiveRecord

mysql,ruby-on-rails,ruby,activerecord,rails-activerecord
Lets say I have a Cat table and each cat has a unique color. Is there an activerecord method I can use to get the red and the blue cat in one query. My goal is a faster query than having to find each one individually with Cat.where(color: red) then...

Error when adding a column with several options

ruby-on-rails,ruby-on-rails-3.2,rails-activerecord
I have the following migration in the system I'm working on: class CreateEstoqueGruposProdutos < ActiveRecord::Migration def change create_table :est_grupos_produtos do |t| t.integer :grupos_produtos_nivel_id, :null => false, foreign_key: { references: :est_grupos_produtos_niveis, on_update: :cascade, on_delete: :restrict }, index: { with: [:id], unique: true, :name => 'unique_grupos_produtos_id_nivel' } t.timestamps end end end It...

not in rewhere active record rails

ruby-on-rails,ruby,activerecord,rails-activerecord
How can I use the 'not' together with the 'rewhere' statement in active_record? bad example (not working): Field.where(name: 'Bukk').rewhere.not(name: 'Tolgy') ...

How to integrate :missed days with :committed days in habits.rb?

ruby-on-rails,ruby,integer,rails-activerecord,days
How can we integrate t.integer :missed with t.text :committed so that when a User checks off he :missed 3 :committed days in a :level he has to restart the :level? for each :missed day he checks off, an additional :committed day is added back into the :level so that he...

Convert SQL “Concat” to Activerecord

mysql,sql,ruby-on-rails,rails-activerecord
I have a SQL query like this: select * from clients where 'Ed Sheeran' like Concat(Concat('%',first_name),'%') or 'Ed Sheeran' like Concat(Concat('%',last_name),'%') I want to convert my query to active record. I'd attempted to convert it: Client.joins(:cases).where(''Ed Sheeran' LIKE CONCAT(CONCAT('%'first_name, )'%')' OR 'Ed Sheeran' LIKE CONCAT(CONCAT('%'last_name, )'%')') but I've got this...

Get value of atomic counter (increment) with Rails and Postgres

ruby-on-rails,postgresql,rails-activerecord,atomic,sidekiq
I need to atomically increment a model counter and use its new value (processed by a Sidekiq job). At the moment, I use Group.increment_counter :tasks_count, @task.id in my model which atomically increments the counter. But I also need its new value to send a notification, if the counter has e.g....

Primary key is null when left join is used

ruby-on-rails,ruby,left-join,rails-activerecord
When I use this request @questions = Question.joins("left join answers as a on a.user_id = #{current_user.id} and a.question_id = questions.id").select('questions.*, a.*') Question.id is null. Does anyone know why? Maybe it needs an alias or something like that. My schema: class Answer: belong_to: User belongs_to: Question end class User: has_many: answers...

Rails preview update associations without saving to database

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
I want to preview what the model will look like when saved without currently saving to the database. I am using @event.attributes = because that assigns but does not save attributes for @event to the database. However, when I also try to assign the audiences association, Rails inserts new records...

Learning Rails -> Setup a Cookbook App

ruby-on-rails,rails-activerecord
I'm new to Rails and trying to setup a cookbook app for practice. Here is what I have so far: DB Setup - 3 tables (simplified for readability) recipes (id, name, description) recipe_ingredients (id, recipe_id, ingredient_id, qty, unit) ingredients(id, name) Models class Recipe < ActiveRecord::Base has_many :recipe_ingredients, dependent: :destroy has_many...

Issue with saving and validating temporary virtual attributes which come from form inputs

ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord,rails-models
I have two models: Project. Item. A project has many items, and an item belong to a project. class Project < ActiveRecord::Base attr_accessor :main_color, :secondary_color, :tertiary_color has_many :items accepts_nested_attributes_for :items validates :main_color, :presence => true validates :secondary_color, :presence => true validates :tertiary_color, :presence => true end class Item < ActiveRecord::Base...

how to setup two user_id columns in one model in rails?

ruby-on-rails,rails-activerecord,rails-models
I have two models class User has_many :disputes end class Dispute belongs_to :user end So Dispute has :user_id, but my problem is that a Dispute has 2 sides - the claimant and the indicted, both of which are users. I tried to solve this problem by creating two columns: :claimant_id...

How to group all recorders that start with a number together

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,rails-activerecord
I have a simple rails blog that displays the list of all artist and I would like to group all those that start with a number in a group called 0-9, followed by a, b, c, d where a, b, c, d displays artists that start with those respective characters....

What makes a rails param?

ruby-on-rails,activerecord,model-view-controller,rails-activerecord,strong-parameters
I've built a couple rails sites so far (really enjoyable framework to use) but I'm gradually noticing that my monkey-see-monkey-do method of learning strong params has apparently left a gap or two in my understanding. Looking below at a simple example (the Recipe Box by mackenziechild) def recipe_params params.require(:recipe).permit(:title, :description,...

why rails docs says to put inverse_of on a belongs_to relation

ruby,ruby-on-rails-4,rails-activerecord
Why rails docs says to use inverse_of in has_* - belongs_to relations? class Customer < ActiveRecord::Base has_many :orders, inverse_of: :customer end class Order < ActiveRecord::Base belongs_to :customer, inverse_of: :orders end Anyway while playing with rails i can see it's raising an error when you put inverse_of in belongs_to association. Are...

Rails 4 - How to dynamically reference an unknown table related to itself?

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
In an attempt to build an automated filter system for a dynamically generated index view, I came upon the need to handle related records on the same table, (for example, a Task belongs to Tasks through a parent_id field set as the foreign key. How would one reference the self...

Rails : Return an object to show user's profile completeness

ruby-on-rails,rails-activerecord
I have a User Model and would like to return to the controller and view what parts of the user's profile are complete and what parts are not. So it would return for example an object "profile_completeness" which can be used like so : @user.profile_completeness.personal_info Which would be true if...

Foreign key is allowed to be NULL?

ruby-on-rails,ruby,rails-activerecord
I have a table which MUST have a case_id that is valid and exists, and the record should not be created unless it exists. I should not be able to pass a NULL case_id. It looks like: # == Schema Information # # Table name: medical_intervention_expert_answers # # id :integer...

Ruby on Rails 4 Nested Forms with Active Record

ruby-on-rails,ruby-on-rails-4,rails-activerecord
I am new to Rails and just building my first app (coming from a PHP and .NET background and loving it btw) but I have run into a problem that I am struggling to find an answer to, even though I am sure there is an easy one!! My project...

Does Rails allow conditional validations for validates_associated?

ruby-on-rails,rails-activerecord
Does Rails allow conditional validations for validates_associated? I'm seeing the following on Rails 4.2.0. Am I trying to do it incorrectly? Models: class User < ActiveRecord::Base has_many :books validates_associated :books, if: :should_validate_book? def should_validate_book? return false end end class Book < ActiveRecord::Base belongs_to :user validates_presence_of :title end The presence validation...

Is there way to call a table as a variable in Active Record?

ruby-on-rails,coding-style,rails-activerecord
The title is a bit confusing, so let me explain. I have 3 Model classes called Table1, Table2, and Table3. All three tables have the "total" column. This is what I want to be able to do: index = either 0, 1, or 2 tableNames = ["Table1", "Table2", "Table3"] tableNames[index].total...

Rails Active Record .where statement optimization

ruby-on-rails,rails-activerecord,where
I'm building an ecommerce site and want to use an active record where statement to find shipments that are scoped to a certain supplier and certain shipment states. Here's what I have now: Spree::Shipment.where("stock_location_id = ? and "state = ?", spree_current_user.supplier.stock_locations.first.stock_location_id, 'shipped' || 'ready') I've found that this results in...

Presenting `belongs_to` association via Grape Entity in Rails 4

ruby-on-rails,ruby,rails-activerecord,grape,grape-entity
Given these 2 models: class Conversation < ActiveRecord::Base has_many :messages, :class_name => 'Message', inverse_of: 'conversation' class Entity < Grape::Entity expose :id, :title expose :messages, :using => 'Message::Entity' end end class Message < ActiveRecord::Base belongs_to :conversation, :class_name => 'Conversation', inverse_of: 'messages' class Entity < Grape::Entity expose :id, :content expose :conversation, :using...

Search with foreign key association

ruby-on-rails,ruby,rails-activerecord
I have an association that looks like: belongs_to :question, -> { where lang: I18n.locale }, class_name: "Translation", foreign_key: 'question_tid', primary_key: 'id' has_many :questions, class_name: "Translation", foreign_key: 'id', primary_key: 'question_tid' Schema looks like: # # id :integer not null, primary key # question_tid :integer # category_id :integer # default_answer_tid :integer #...

How to obtain different type of collections for the same Model in an Association in Rails 4?

ruby-on-rails,ruby,rails-activerecord,models,model-associations
In my application I have a User model and a Job model. Users can post many jobs, and other users can apply to these jobs by posting proposals. The job poster can then select a user from the list of users who have applied, later this user will be assigned...

rails 4: active record associations: how to list all tasks from a project?

ruby-on-rails,ruby,rails-activerecord,model-associations
I have a created a demoapp, where users can have many projects, and each projects can have many tasks. When I am logged in as a user, and visit project_path, all available and related projects to this user are listed. But now, how can I list all tasks related to...

How do you run ActiveRecord `find_each` to a materialized view in postgres

postgresql,rails-activerecord,materialized-views
Because I am pulling thousands of records from my materialized view Matview, I'd like to use find_each to break it up into batches to free up memory. However, when I run the following: Matview.where('p_id > 100').find_each {|m| m } I get the following eror: PG::SyntaxError: ERROR: zero-length delimited identifier at...

Rendering partial from another controller breaks app - undefined method `text' for #

ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord
I'm trying to render partials from another view posts/_index and posts/_new and controller Posts, into another view welcome/index. The posts/_index loads fine, but I can't figure out/understand why the posts/_new throws an error for the :text method which is only defined in the database migration, which I thought would be...

Rails: Aggregate queries through association

ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord
In rails, is there an ActiveRecord way of doing an aggregate query through a has_many :through association? EDIT: I'm looking for a database-driven solution, not a bunch of Ruby iterating/munging. EDIT #2: I screwed this up. The Venue model is also many-to-many with Show. For instance. Imagine something (contrived) like...

Rails 4 has many through

ruby-on-rails-4,activerecord,rails-activerecord
Hi there I'm a rails newbie and am having a hard time understanding an error I am getting. I have many to many relationship that consists of Project -> one to many project_numbers (billing numbers) project_number -> has id, project_id(fk), task_name and hours associated with a task. Associate-> Employee/Developer performing...

validate strict with custom exception not working

ruby,rails-activerecord,ruby-on-rails-4.2
I have a model which has a standard validates method but with the strict option and a custom exception. class Comment < ActiveRecord::Base validates :resource,:user,:body, presence: true, strict: Exceptions::InvalidRequestParams end exception module is in controller concerns and tests are working fine, so is app. But when I try to access...

Rails - Specify a fixed length column in DB migration with PostgresSQL

ruby-on-rails,postgresql,activerecord,rails-activerecord,rails-migrations
It seems that among column modifiers there's only :limit, which specifies the maximum length of this column. However, what if I want to specify the length to be exact? For example a cellphone number must have 11 digits, so I won't want the user to enter an invalid number. Of...

Average per hour inverval - Rails

ruby-on-rails,ruby,sqlite,rails-activerecord
[Info: Ubuntu 14.02, ruby 2.2.3p110, Rails 4.2.1] I need a rake task to fetch the average inserts per one hour range [like 00:00 to 00:59] from the DB (SQLite). I was trying to do something like: namespace :db do task results: :environment do tweet = Tweet.group('date(created_at)').group('hour(created_at)').average() puts "#{tweet}" end end...

Rails - Optimistic locking always fires StaleObjectError exception

ruby-on-rails,ruby,rails-activerecord,optimistic-locking
I'm learning rails, And read about optimistic lock. I've added lock_version column of type integer into my articles table. But now whenever I try to update a record for the first time, I get StaleObjectError exception. Here's my migration: class AddLockVersionToArticle < ActiveRecord::Migration def change add_column :articles, :lock_version, :integer end...

Rails 4.2: Unknown Attribute or Server Error in Log

ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord,actionview
I have a form with a select_tag and options_from_collection_for_select that I can't seem to get to pass. In the view, when the upload id is set to uploadzip_id I get a 302 redirect and when it's set to uploadzip_ids, I get a Unknown Attribute error. I'm a bit confused as...

ruby on rails sum fields after group_by

ruby-on-rails,ruby,postgresql,rails-activerecord
before I start I just want to tell that I tried some aproaches from similar topics but they don't work well with my case. I have orders that I am grouping by days (using group_by(&:created_at) method). Now I want to sum "total" field from orders that are on particular days....

Ruby on Rails - Why can't I use ActiveRecord::Base methods? Where to use?

ruby-on-rails,ruby-on-rails-4,rails-activerecord,each,collect
I've been trying to use ActiveRecord::Base methods such as .each and .collect in my application but I keep getting undefined method errors! Perhaps I have a shaky knowledge of Ruby. It seems like I can't use these methods in my controller, methods or views? For example, the code below will...

Convert PG::Result to an Active Record model

ruby-on-rails,ruby,rails-activerecord
pg-ruby allows you to send multiple queries to the database in one shot, which helps minimize the number of trips made to the database: results = [] conn.send_query('QUERY1;QUERY2;QUERY3') conn.block while result = conn.get_result results << result end Given that for any result I already know the Active Record model, what's...

counter_cache doesn't works

caching,ruby-on-rails-4,activerecord,rails-activerecord
If I execute in rails console (dev or in unit test ENV) : u = User.first puts u.topics_number # 0 Topic.create!(user: u) puts u.topics_number # 0 puts u.reload puts u.topics_number # 1 where topics_number is counter_cache in Topic class like : belongs_to :user, counter_cache: :topics_number topics_number is in table users....

Ruby on Rails - how would I change the order of posts displayed to newest at the top of page?

ruby-on-rails,ruby,rails-activerecord
I'm creating a simple house listing page to get to grips with Rails and I currently have an add post page set up which posts to the index page however the newest post is displaying at the bottom of the page. How could I reverse the order of my posts...

Should I make new table for storing user's address in Rails

ruby-on-rails,database,sqlite3,rails-activerecord,normalization
I have created a rails app and my "users" table goes like this create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.string "password_hash" t.string "password_salt" t.integer "country_id" t.integer "state_id" t.integer "pincode" t.string "address" t.string "phone_no" t.float "latitude" t.float "longitude" Other tables states , country , posts Associativity: user...

Proper way to serialize json in database with rails [closed]

ruby-on-rails,json,postgresql,rails-activerecord
Let's say that I have this kind of json. In rails, I have three models: Section that have many Questions And Questions have one Answer What is the proper way to save/update it in database ? Thanks in advance for any help { "id": 1, "section_name_fr": "Section1", "section_number": 1, "questions":...

Rails console setting limit to one on queries

ruby-on-rails,rails-activerecord,rails-console,ruby-on-rails-4.2
When I run ActiveRecord queries, the Rails Console seems to be appending LIMIT 1 to my queries. So I have a sheet which has_many slots. When I query Slot.find_by(sheet_id: 96), I get: Slot Load (2.3ms) SELECT "slots".* FROM "slots" WHERE "slots"."sheet_id" = ? LIMIT 1 [["sheet_id", 96]] => #<Slot id:...

Choosing a specific row in a table in rails

ruby-on-rails,ruby,ruby-on-rails-4,model,rails-activerecord
I have a migration and model with a table called medications. I need to pick a specific row from the medications table. I also am trying to filter out all medications that don't have the current user's id. Here is the current code I have. Medication.find(:name, :conditions => { :user_id...

Rails 4 active record validation - Conditionally validate interdependent presence of 4 attributes

ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord
I have a form with 10 attributes. Among them I have 4 attributes which I need to apply what I'd call a"mutually conditional presence" Active Record validation. these attributes are address_line_1 zipcode state country It means that if the user fills ONE of them then ALL the others have to...

Validate that original value was nil in Rails

ruby-on-rails,ruby-on-rails-4,rails-activerecord
I want to add a validation to the model to check that a field (string) could be set to something only it's original value is nil. How can I do this? Actually two subquestions are: Is there a standard way of doing it If custom validation is required, how can...

Proper ActiveRecord associations for self-joined classes

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
I have been modifying an online Rails tutorial to suit my specific needs, and I've found myself out of my depth. A little clarity would be much appreciated. My code is below my question. At this point, if dan and rob are instances of class User, and I call dan.add_supervisor(rob)...

Rails 4 Attempting to save Multiple Records to single Model

ruby-on-rails-4,rails-activerecord,simple-form,omnicontacts-gem
I am using the Omnicontacts Gem to pull a list of contacts. So far that works. I can get the contacts and use them to populate a form so I can pass them to my Contacts Controller to be saved in the Contact Model. I have looked at the Rails...

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...

polymorphic association belongs to User

ruby-on-rails,model-view-controller,rails-activerecord,polymorphic-associations
I have a comments model which is a polymorphic association which is involved with Statuses and Photos. How can I create this polymorphic association to also belong to a User so that when a user creates a comment under statuses or photos it will also recieve the current_user id? this...

How to find items with *all* matching categories

ruby-on-rails,ruby,postgresql,rails-activerecord
I have two models, Item and Category, joined by a join table. I would like to query Item to find only items that match a list of categories. My models look like: class Item < ActiveRecord::Base has_and_belongs_to_many :categories end class Category < ActiveRecord::Base has_and_belongs_to_many :items end I can easily find...

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...

ActiveRecord where field = ? array of possible values

ruby-on-rails,rails-activerecord
I want to do Model.where('id = ?', [array of values]) How do I accomplish this look up without chaining OR statements together?...

Rails to_json include a method has args

ruby-on-rails,rails-activerecord
In my Rails app,I have following codes: MemAccount Mode class MemAccount < ActiveRecord::Base attr_accessor :current_mem def followstatus SntFollow.where({:from_id=> current_mem.id}).pluck('to_id').include? id end end Controller: def search _items = MemAccount.select(:avatar,:nc,:id,:followers).where("nc like '%#{params[:search]}%'") render json:{ :items => _items }.to_json(:methods=>["followstatus"]) end How can I set the MemAccount instance attr current_mem for the mem lists,not...

How to query multiple tables with ActiveRecord?

ruby-on-rails,rails-activerecord
I am trying to figure out how to write the equivalent of this query in ActiveRecord: SELECT id FROM projects, neighborhoods WHERE ST_WITHIN(projects.lonlat, neighorhoods.the_geom); I tried several approaches, including Neighborhood.select(:id).from('projects').where("ST_WITHIN(projects.lonlat, neighorhoods.the_geom)") But the resulting query always resolves to a single table. Can anyone help me out?...

How to validate a binary field using Ruby on Rails?

mysql,ruby-on-rails,ruby,encoding,rails-activerecord
I want to ensure that a binary field has always value. I added a validation code like below. class Foo < ActiveRecord::Base validates :b, presence: true end However, the change seems to cause the error. $ rails c > Foo.create(b:File.read('b.jpg')) ArgumentError: invalid byte sequence in UTF-8 The error doesn't always...

Rails 4 - order by related models created_at - activity

mysql,ruby-on-rails,ruby-on-rails-4,order,rails-activerecord
In my rails app I have few related models for example: Event has_many :comments has_many :attendents has_many :requests What I need is to order by 'created_at' but not only main model (Event) but also related models, so I will display on top of the list event with most recent activity...

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...

How can I sync my data from an external database in Rails?

ruby-on-rails,sql-server,rails-activerecord
I'm importing information from another database into my Rails database. At the moment I've queried the database to get all records from a table and then I create new objects of my model and assign the values. I'm wanting to detect if a record has been updated though, and if...

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...

how filter model1 has_many model2 has_one model3 (polymorphic)?

ruby-on-rails,rails-activerecord
I have model User, then has_many :estates, dependent: :destroy Model Estate with polymorphic association has_one :location, as: :locatable, dependent: :destroy in Location migration, i have class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :address t.decimal :lat, {:precision=>10, :scale=>6} t.decimal :lng, {:precision=>10, :scale=>6} t.references :locatable, polymorphic: true, index:...

How to upvote a photo and automatically downvote the other photo?

ruby-on-rails,postgresql,rails-activerecord
I have a show view for a contests model that displays 2 random photos: <% if @contest.photos.size < 2 %> <p>not enough photos in this contest</p> <% else %> <%= link_to (image_tag @random_photo1.image.url(:thumb)), upvote_path(id: @contest.id, photo_id: @random_photo1.id) %> <%= @random_photo1.score %> <%= link_to (image_tag @random_photo2.image.url(:thumb)), "#" %> <%= @random_photo2.score %>...

Rails is throwing an error the first time an attribute is assigned to my model

ruby-on-rails,ruby-on-rails-4,rails-activerecord
I have a rails model that keeps track of other models in an app. (unusual, but necessary for this project). When I try to assign the attribute model_name I get an error that occurs once, but then doesn't occur again. AppModel model_name created_at updated_at ---------------------------------------- User Question Post Answer In...

How to use Self Join to separate data with no relationships in RAILS 4

ruby-on-rails,ruby-on-rails-4,rails-activerecord
I am building a prototype for a inventory system for a clothing store. This app manages item markdowns, original price,Markdown price, colour, availability. the app imports an excel file and maps the columns and the rows of the excel to a model. there are 6 columns in total, both male...

Rails :counter_cache with custom query association

ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord,database-performance
I have a model like this: class Vote belongs_to :content, counter_cache: true end class Content has_many :votes has_many :votes_up, -> { where(positive: true) }, class_name: 'Vote' has_many :votes_down, -> { where(positive: false) }, class_name: 'Vote' end If I create a proper migration, when I execute mycontent.votes_count, it will not make...

Rails, jRuby, ArgumentError: wrong number of arguments calling `to_sql` (2 for 1)

ruby-on-rails,ruby,postgresql,rails-activerecord,jruby
Cloned new rails project, and tried to run rake db:migrate am getting the following error message. Backtrace: rake db:migrate --trace ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment rake aborted! ArgumentError: wrong number of arguments calling `to_sql` (2 for 1) home/raj/.rvm/gems/jruby-1.7.12/gems/activerecord-jdbc-adapter-1.3.16/lib/arjdbc/jdbc/adapter.rb:535:in `select'...

Odd rake db:migrate output

ruby-on-rails,ruby,rake,rails-activerecord
Why does rake db:migrate run Execute db:schema:dump my output is all screwed up (showing SQL). Looks like this: ActiveRecord::SchemaMigration Load (0.5ms) SELECT "schema_migrations".* FROM "schema_migrations" (3.7ms) SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete FROM pg_constraint c JOIN pg_class...

How can I check for a record before creating it in my seeds file?

ruby-on-rails,ruby-on-rails-4,rails-activerecord
My Rails seeds file looks like the following... Club.create([ {name: 'Atlanta Falcons', moniker: 'Falcons', city: 'Atlanta', state: 'GA', zipcode: '0', code: 'ATL', conference: 'NFC', division: 'South', primary_color: 'BD0D18', secondary_color: '000000', tertiary_color: 'FFFFFF', quaternary_color: 'DCE0E5', quinary_color: '', weather_location: 'Atlanta+GA+USGA0028:1:US', plays_in_dome: '1', time_zone: 'Eastern Time (US & Canada)', logo_image: 'atl.gif', word_art_image: 'title.gif',...

Apply an 'or' to an inner joined where clause ActiveRecord

ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-3.2,rails-activerecord
Model: class QueueList < ActiveRecord::Base has_many :times self.today joins(:times).where(times: { period_type: 'on', date: Date.today} || times: { period_type: 'from', date: Date.today }) end end The above model contains a list of times. Because :times can be in two different period_types, I have to apply an "OR" to this query. Is...

Find duplicated users using Ruby [closed]

ruby,rails-activerecord
I am having trouble finding a way to find from a single query if there are users duplicated in my database. How could I query to find dupped users in Ruby using ActiveRecord? The database structure is here: http://www.collectivestep.com/discoursedb/...

Why am I able to bypass the has_one relationship with the << operator?

ruby-on-rails,ruby,rails-activerecord
Here's the example relationship: class User < ActiveRecord::Base has_one :group, through: :group_membership has_one :group_membership end class Group < ActiveRecord::Base has_many :users, through: :group_memberships has_many :group_memberships end class GroupMembership < ActiveRecord::Base belongs_to :group belongs_to :user end Why am I able to do the following? Group.first.users << User.first Group.second.users << User.first I...

Rails - Returning list of incorrect ids

ruby-on-rails,ruby,ruby-on-rails-3,rails-activerecord
I have an app including Dog, Events and Booking models. Each event has many bookings, each dog has many bookings but each booking belong to an event and has one dog. On the view for Events it should list all bookings with that id and the details of the linked...

Property from attr_accessor does not show when I render json

ruby-on-rails,ruby-on-rails-4,rails-activerecord,attr-accessor
In Rails, I have a User model. I added attr_accessor :scoreto the model. If I render the JSON for one user, I do not see the "score" attribute. Why is this? user = User.find(3) user.score = 55 render json: user ...

Rails 4.1 ActionController::UnknownFormat in index method

ruby-on-rails,ruby-on-rails-4,devise,rails-activerecord,actioncontroller
I am a noob. After an exhaustive search of other questions, I was unable to find similar posts with clear and correct answers. First, let me explain that my app has nested associations as follows: User has one customer Customer has many accounts User has many accounts through customer So...

Using substring in Rails query the safe way

mysql,ruby-on-rails,ruby,rails-activerecord,sql-injection
I'm currently writing a query to look in a table some grouped results in order to build an alphabetical pagination index. The query I have looks something like the following (based on this answer): criteria = "substr(%s, 1, 1)" % field_name Posts.select(criteria).group(criteria).order(criteria).count(:id) Now I would like to improve this query...

Fetch records from a table based on the condition in associated table

sql,ruby-on-rails,postgresql,activerecord,rails-activerecord
I have two models School and Expense where school has many expenses, Expense has an attribute named cost I'm trying to fetch only those schools with their expense cost greater than a certain value, let's say 1000, I tried this query School.includes(:expenses).where("lower(schools.name) LIKE '%a%' and expenses.cost >= 1000").select('*').from('schools, expenses') The...

Rails: Sorting ActiveRecord with hyphens

ruby-on-rails,rails-activerecord
Friends, I have a simple query like this one: ContactForm.where(:is_active => true).order(:name => :asc) But I want one of my records to appear always first, so I prefixed it with a couple hyphens "--", however, the order clause is not swapping that record to the first place, in fact it's...

Rails - Active Record Query Not Querying on Variable Assignment (Want to Load Eagerly)

ruby-on-rails,postgresql,rails-activerecord
This is a query that returns all question submissions that have rubric_item_evaluations with present=true and has a rubric item with @rubric_item.id submissions_to_update = QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations => {:present => true , :rubric_item_id => @rubric_item.id}) Then we destroy rubric item @rubric_item.destroy Then we iterate through the submissions to regrade submissions_to_update.each do |submission| submission.grade!...

RoR: removing sensitive field from response

ruby-on-rails,ruby,rails-activerecord
Is there any way to remove sensitive fields from the result set produced by the default ActiveRecord 'all', 'where', 'find', etc? In a small project that I'm using to learn ruby I've a reference to User in every object, but for security reasons I don't want to expose the user's...

Delete children when parent type changes

ruby-on-rails,rails-activerecord
I have this code: class FlexField < ActiveRecord::Base has_many :flex_field_values, class_name: 'FlexFieldValue' after_save :delete_flex_values def delete_flex_values if self.field_type != 'list' self.flex_field_values.delete_all end end The goal is to delete all values if the type isn't a list. Now what is happening is that as soon as I set the type to...

check if record exists before saving to db - Rails, Twitter, ActiveRecord

ruby-on-rails,ruby,activerecord,twitter,rails-activerecord
I am using a Twitter Gem to pull and save Tweets from user's timeline. Before saving each message, I want to check if this record already exists by comparing the new message's tweet_id to the array of tweet_id's already saved in the db. No matter what I try, I am...

Create a deep copy of a record?

ruby-on-rails,ruby,rails-activerecord
I need to be able to copy a record. By that I mean that: All the references need to be deep copied. For example, if I have a Case and it has a patient_id linking to a patient, to copy a case would mean to create a copy of the...

Avoiding Float truncation in Rails 4

ruby-on-rails,ruby,postgresql,rails-activerecord
I have an Active Record model that takes a Float attribute and a corresponding table: # app/models/test.rb class Test < ActiveRecord::Base end # db/schema.rb ActiveRecord::Schema.define(version:20150208185300) enable_extension "plpgsql" create_table "tests", force: true do |t| t.datetime "created_at" t.datetime "updated_at" t.float "size" end end When I persist a Test everything looks fine: Test.create(size:...

Rails how should I store city and state for a customer

ruby-on-rails,ruby,rails-activerecord
I have a Ruby on Rails app with a Customer model that needs a related city/state. Adding a string column for the state could cause my coworkers to miss-type the location and I would have a harder time finding all the customers in a given city. Creating a model for...

Rails 4: Using unique alphanumeric identifier (not primary key) to join tables

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,rails-activerecord
Rails 4, Active Record, Nitrous.io, Heroku, PostgreSQL. The most_important_table in the Rails app I am coding contains records that each have a unique identifier (examples: "912828J27", "US38141EC238"), call it uniq_alphanum_identifier. My application (LEFT OUTER) joins several other tables' data ON most_important_table.uniq_alphanum_identifier. Since I am not using my records' primary key...

Ruby on Rails Active Record create: No Method Error

ruby-on-rails,rails-activerecord
Doing my first steps with Ruby on Rails, I am trying to create my database model with active records. For now, I have done this: rails generate model seminar title rails generate model student firstname lastname Than I ran rake db:migrate and edited the .rb files like this: class Seminar...

rails accessing model attributes return nil

ruby-on-rails,rails-activerecord
So I made an Item class from ActiveRecord::Base. I've implemented the show action so that I could see it from items\id. In show.html.erb I have accessed all the attributes and labeled them on the file. When I went to the web page, none of the attributes showed up, only their...

Rails has_one relationship where foreign key is on owning model?

ruby-on-rails,rails-activerecord
I have a Photo and Photoset model: A Photoset should have many photos and one primary_photo. A Photo should belong to many Photosets and can be the primary_photo of many photosets. However I am stumped as how to setup the primary_photo relation. I was envisioning adding a primary_photo_id to photosets...

Heirarchical, in-memory associations without poor workmanship

ruby-on-rails,ruby,activerecord,rails-activerecord
I have a need for a nested, hierarchical data structure extracted by ActiveRecord, all early-loaded of course, that I can JSONify. TaskSet, Task, Todo, and LineItem are all associated as the latter being a child of the former. As is apparent, I am no Ruby genius: the best I've come...

Creating a feed => NoMethodError: undefined method for ActiveRecord_Associations_CollectionProxy

ruby-on-rails,rails-activerecord,has-many-through,model-associations,rails-postgresql
I am implementing a feed of all cards belonging to the tags a user has subscribed to and I get the following error. It's probably something trivial but I can't pinpoint what needs work. NoMethodError: undefined method `cards' Tag::ActiveRecord_Associations_CollectionProxy:0x007fbaa46239f8> Here are my models: class User < ActiveRecord::Base has_many :cards, dependent:...

Count objects after using activerecord joins

ruby-on-rails,activerecord,rails-activerecord
I just noticed that using .size or .count on a query that has joins gives unexpected results. User.some_scope.size #=> 10 User.joins(:associations).some_scope.size #=> 10 + associated object count How do I get the count of Users that fit the scope no matter what I join onto the table? Some of the...

Is it safe to override .hash on an ActiveRecord?

ruby-on-rails,rails-activerecord
The default ActiveRecord hash implementation is to return the hash of the id. This is great for persisted instances. It's terrible for un-persisted instances especially because Rails defaults to BasicObject.== for ActiveRecord instances with no IDs. So all unsaved ActiveRecord instances will have the same hash and not be equal....

Rails uniq Public Activity

ruby-on-rails,postgresql,activerecord,rails-activerecord,public-activity
t = PublicActivity::Activity.arel_table @activities = PublicActivity::Activity.where( (t[:trackable_type].eq("Lesson").and(t[:trackable_id].in(@my_lessons_ids))) .or(t[:trackable_type].eq("Post").and(t[:trackable_id].in(@my_posts_ids))) .or(t[:trackable_type].eq("WallPost").and(t[:trackable_id].in(@my_wallposts_ids))) .or(t[:trackable_type].eq("Comment").and(t[:trackable_id].in(@my_comments_ids))) .or(t[:trackable_type].eq("Course").and(t[:trackable_id].in(@my_courses_ids)))...

Rails associations, how can I specify this relationship?

ruby-on-rails,activerecord,rails-activerecord
OS: Windows 7 Rails: 4.2.0 Hello, If I have two models lets say Game, and Team. One game can have many teams, but teams can also belong to many games. I can't seem to figure out the right way to do this, Belongs_to_many does not exist, and I don't think...