Menu
  • HOME
  • TAGS

Finding non-eager loaded relations used in a Rails view

ruby-on-rails,ruby,activerecord

The bullet gem can be used to log n+1 queries. It works pretty well for me.

activerecord query for a an array of arrays

ruby-on-rails,activerecord

You can use includes. u = User.includes(:received_notifications, :alert) .where("alerts.frequency_discussion_alerts = ? AND notifications.sent_email = ?", 1, false) .references(:notifications,:alerts) Now in batch, you can fetch users and do your job. u.find_each { |u| u.received_notifications } ...

Multiple many-to-many association between two models

ruby-on-rails-4,activerecord,associations

I guess your association set up should be something like this #user.rb Class User has_many :company_admins has_many :companies, :through => company_admins has_many :followers has_many :followed_companies, :through => followers, :source => :company end #company.rb Class Company has_many :company_admins has_many :users, :through => company_admins has_many :followers has_many :followed_users, :through => followers, :source...

Activerecord migration error on postgresql

ruby-on-rails,postgresql,activerecord

Ok i found the problem. i think that the error message is the same as before but he refer to a other table called "confidence_indices". The error come from "indice" word.. when i delete it i have no problem.

Redirect if ActiveRecord::RecordNotUnique error exists

ruby-on-rails,postgresql,activerecord,error-handling

Just the way you catch every other error begin Transaction.create!(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now) rescue ActiveRecord::RecordNotUnique redirect_to root_path end ...

ActiveRecord Survey Model ActiveRecord Associations for Doctor -> Patient

ruby-on-rails,activerecord,associations

Well, first thing to note is that you are performing multiple queries for something you can actually pop into one procedural scope. I have no idea what the big picture is to your needs so I could be totally off about what is more important for you. To answer your...

Rails 4 many-to-many associations nightmare

ruby-on-rails,ruby,activerecord,many-to-many,associations

It looks like you're using plural names for the join table belongs_to associations. Try changing to: class LocationsTrip < ActiveRecord::Base belongs_to :location belongs_to :trip end ...

Group by class in Rails 4.0

ruby,ruby-on-rails-4,activerecord

What you really need is actually: Product.group(:product_type) Let's assume we have data like this: Product.create(name: "TV", product_type: "Electronics") Product.create(name: "Diablo", product_type: "Computer Games") Product.create(name: "Basics", product_type: "Books") Product.create(name: "Radio", product_type: "Electronics") Product.create(name: "Assassins", product_type: "Computer Games") Product.create(name: "Cooking", product_type: "Books") When you perform code you've provided it returns single result:...

ActiveRecord query with OR and where.not

sql,ruby-on-rails,ruby,ruby-on-rails-4,activerecord

Discussion.includes(:discussion_tags).where('discussion_tags.taggable_id IS NULL or discussion_tags.taggable_type != ?', 'Product').references(:discussion_tags)

Rails Active Record group or ignore duplicate results from query

mysql,ruby-on-rails,postgresql,activerecord,rails-activerecord

You should be able to chain .uniq onto the end of the query to bring back unique records. Or you could try .distinct http://apidock.com/rails/ActiveRecord/QueryMethods/distinct...

Ruby ActiveRecord: How to connect two rooms with an exit

ruby,activerecord,orm,rails-activerecord,adventure

To get room.neighbours working, I believe you would first need to change belongs_to :room_dest, foreign_key: "room_dest_id", class_name: "Room", dependent: :destroy to belongs_to :neighbour, foreign_key: "room_dest_id", class_name: "Room" Note that I removed the dependent: option because you probably don't want to destroy Rooms when Exits are deleted. You want dependent: :destroy...

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

ruby-on-rails,ruby,activerecord

Use as_json. It's what to_json uses under the hood, and accepts all the same options but returns a Hash.

Rails: select model

sql,ruby-on-rails,activerecord,associations

See MySQL: Select records where joined table matches ALL values for how to do it in sql. For a simpler method, which makes a series of simple queries instead of a single complex query, you could do this: #starting with the services in an array called @services #(which could come...

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

sql,ruby-on-rails,postgresql,activerecord

Underscore is a wild card in sql, so try 'above_the_line'.

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

Best practice for sharing translation of Active Record attributes

ruby-on-rails,activerecord,internationalization,yaml,rails-activerecord

se: common: &common name: "Namn" activerecord: attributes: user: <<: *common town: "Stad" admin: <<: *common level: "Nivå" pet: <<: *common company: <<: *common food: <<: *common ...

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

ruby-on-rails,ruby,postgresql,activerecord,sidekiq

You need to lock the model: account = Account.first account.with_lock do # This block is called within a transaction, # account is already locked. account.balance -= 100 account.save! end You can read more about it here: http://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html...

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

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

You can use the hash options of the ActiveRecord::Core#new method in your controller: @user = User.new(user_params.merge(referrer_url: create_url)) Or move all that into a separate method for a clearer and more readable code: @user = User.new(user_params_with_additional_data) private def user_params_with_additional_data user_params.merge(referrer_url: create_url) end ...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

“NameError: uninitialized constant” on existing ID

ruby-on-rails,ruby,activerecord

I'm kicking myself. The issue was that the models actually had belongs_to :admin_district_id, and once they were changed to belongs_to :admin_district, the issue was resolved. I think the issue came about when generating the models - I must have used admin_district_id:references instead of the correct admin_district:references....

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

ruby-on-rails,ruby,activerecord

While it it not recommended to override default ActiveRecord::Base's constructor, it accepts a hash of attributes to be set for the object, thus you can do something like: class Category < ActiveRecord::Base self.table_name = Tables::CATEGORIES def initialize(name) super({ active: true, name: name }) end end ...

Query by two column version number in rails

ruby-on-rails,ruby,activerecord

I think the correct SQL query would be as follows: major > :major -- check for bigger major OR (major = :major AND minor > :minor) -- check within the same major You can use it in ActiveRecord all right with the placeholder conditions, though you probably should remove the...

Complex rails SQL query

sql,ruby-on-rails,ruby,postgresql,activerecord

You can use having and group methods for this: User.joins(:age_demographics) .where("age_demographics.range IN (?)", ["12 - 17", "18 - 24", "25 - 34"]) .group("users.id") .having("sum(percentage) >= 50") ...

Rails Active Record find every 10th record

sql,ruby-on-rails,activerecord

you can do something like this total = Lang.count ids = (1..total).step(10) Lang.where(id: ids.to_a) After thinking about this. I think if you are looking for a sample the best thing to do is Lang.all.shuffle.first(30) # this returns 30 random rows from the langs table I try to do it as...

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

ruby-on-rails,ruby,activerecord

On your basic example something like this should work. def get_object_from_url url_string class_string = url_string.split('/')[-2] object_id = url_string.split('/')[-1] class_string.camelize.constantize.find_by_id(object_id) end Would require more complicated logic depending on the url's....

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

ruby-on-rails,ruby-on-rails-4,activerecord,devise

A has_one relationship will automatically add the :create_<relationship> and build_<relationship> methods. Checkout the rails guide. You could try this: after_create do create_user_profile(:name => 'username') end Or more likely after_create do create_user_profile(:name => self.username) end ...

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

ruby-on-rails,validation,activerecord

You can use =~ operator instead to match a string with regex, using this you can add a condition in setter methods def resolution=(res) if res =~ /\A\d+x{1}\d+\d/ # do something else # errors.add(...) end end but, as you have already used attr_accessor, you don't have to define getter and...

Complex many-to-many relation in Rails

ruby-on-rails,activerecord,has-and-belongs-to-many

This is the first solution that popped in my mind, and there may be many other ways to do it, but I believe this may arguable be the cleanest. You've got the right general idea, but all you need is a slight modification to the join table. Essentially you'll use...

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

ruby-on-rails,ruby,activerecord

If you want to do it with an after_create hook in your model/user.rb: after_create :update_status def update_status Winner.where(:email => self.email).each do |winner| winner.status = true winner.save end end You might argue updating winners based on a user signing up should be a controller task, not the models though. I am...

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

ruby-on-rails,postgresql,activerecord

Using arel can get you pretty far. The tricky part is how do you not write your entire query using arel's own query syntax? Here's a trick: when building your query using where, if you use arel conditions, you get some extra methods for free. For instance, you can tail...

Rails joining multiple methods and scopes

ruby-on-rails-4,activerecord

The error suggest the output query have clients_count as a column but it is just an alias for COUNT. Try running scopes in rails console and analysing the queries in the log one by one: you say this works Service.with_clients first make sure two scopes combined without pagination work correctly...

How to build object with many relationship

ruby-on-rails,ruby,activerecord

Here is what you can do: def new @user = User.find(current_user.id) @course = Course.find(params[:course]) @group = @user.build_group(course: @course) # you can do @user.create_group!(course: @course) to create # the object in-place instead of in memory. end ...

Active Record Where Clause For Relation In Model

ruby-on-rails,activerecord

I want to select sites of premium user This will do User.includes(:sites).where('users.category = ?', 'premium') Update If sites also have categories like 'wordpress or joomla', how do i apply where clause to select only wordpress sites of premium users For that you need to tweak the query like this...

Store accessor for nested JSON

ruby-on-rails,json,activerecord,jsonb

You're right, unfortunately store_accessor does not allow you to access nested keys. The reason is that store_accessor is basically just a shortcut which defines getter and setter methods: # here is a part of store_accessor method code, you can take a look at # full implementation at # http://apidock.com/rails/ActiveRecord/Store/ClassMethods/store_accessor _store_accessors_module.module_eval...

delayed_job_active_record - Undefined method `any?'

ruby-on-rails,activerecord,delayed-job

This doesn't work because @products isn't an array any more - it's a reference to a job that will get executed at some time in the future You need a rethink of how your setup works. For example your view could poll via Ajax to see if the job has...

Get has_many from ActiveRecord::Relaiton

ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord

Well the below, Book.where(fiction: true).collect { |book| book.pages } can be written as : Page.joins(:book).where("books.fiction = ?", true) Similar way : Word.joins(page: :book).where("books.fiction = ?", true) ...

Rails find_or_create_by with/without where

ruby-on-rails,ruby,activerecord

You can use something called: find_or_initialize_by. It only initializes the record, but doesn't create it. This way, you can override the properties later on: task = Task.where(done: false).find_or_initialize_by(title: 'epic').first task.done = true # or nil or whatever you want! task.save I only saved the first record with task.done = true....

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

ruby-on-rails,activerecord,associations,has-many

Here is your corrected version : class User < ActiveRecord::Base has_many :owned_tasks, class_name: "Task", foreign_key: :owner_id end class Task < ActiveRecord::Base #owner_id belongs_to :owner, class_name: "User" end Why need :foreign_key option ? Specify the foreign key used for the association. By default this is guessed to be the name of...

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

ruby-on-rails,ruby-on-rails-4,activerecord

I recommend creating a Practice model, with each practice having a :start and :end attribute, each typed as a :datetime. If you generate a migration like so: rails generate model Practice start_time:datetime finish_time:datetime That will build a migration for your database, adding the columns you need. Be sure to run...

activerecord not like query

ruby-on-rails,activerecord

As others have pointed out ActiveRecord does not have a nice syntax for building like statements. I would suggest using Arel as it makes the query less database platform specific (will use ilike for sqlite & like for other platforms). User.where(User.arel_table[:name].does_not_match('%Gabe%')) You could also implement this as a scope to...

Rails: Garble data as it leaves the database

mysql,ruby-on-rails,activerecord

I'd just do it in the view - rather than at ActiveRecord data querying layer. My first thought is to implement a Obfuscator class like UserObfuscator - which is basically a decorator. Proof of concept: class UserObfuscator def initialize(user) @user = user self end def id @user.id end def first_name...

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 don't know the exact tables of acts_as_taggable but i think they are named: "taggings" and "tags" knowing this you could do: fetch all tags ActsAsTaggableOn::Tag.where("id in (?)", ActsAsTaggableOn::Tagging.where(taggable_type: 'Node').pluck(:tag_id)) fetch nodes that have tags Node.where("id in (?)", ActsAsTaggableOn::Tagging.where(taggable_type: 'Node').pluck(:taggable_id)) in a class method you can do def self.with_tagged_users Node.where("id...

undefined method `includes' for object instance

ruby-on-rails,ruby,performance,ruby-on-rails-4,activerecord

includes can only be called on ActiveRecord::Relations or ActiveRecord::Base children classes, account seems to be a instace of a model, thus not respond to ActiveRecord::Relation methods like includes. It seems a false positive from bullet as soon as you are only getting account from current_user, although I don't recommend delagations...

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

ruby-on-rails,ruby,activerecord,rescue

in general what may be a solution for your problem is try method (http://apidock.com/rails/Object/try). To make the story short - it returns nil instead of raising exception if method does not exist on specific object

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

There is a big difference between the query you get when you run User.find_by_email and the one that is run by the validation: the former has an extra condition on the disabled column. It would seem that when you've been deleting using you've just be flagging them as deleted rather...

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

ruby-on-rails,activerecord,callback

It'll work without any issue, as Active Record wraps-up these callback methods in a single transaction. Since the object is destroyed in first yield, it seems the later is not feasible (assuming everything is running in one thread). How Rails handles this? No, object isn't destroyed in first yield. Object...

Ruby on Rails 4 count distinct with inner join

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

After doing long chat, we found the below query to work : self.member .engines(:reload) .count("DISTINCT engine_code") ...

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

ruby-on-rails,postgresql,activerecord,jsonb

You should call this as below : Person.where("roles ? :name", name: "32486d83-4a38-42ba-afdb-f77ca40ea1fc") ...

implement has_many through association in rails 4

ruby-on-rails-4,activerecord,has-many-through

Please try this code def inventory_status @employee_inventories = EmployeeInventory.new(employee_inventories_params) if @employee_inventories.save redirect_to inventories_path else render :action => :show end end and in your view <%= link_to 'Request for inventory', inventory_status_inventory_path(@inventory, employee_inventory => {:employee_id => 1, :status => 'test'}), :class => 'btn btn-success' %> hope this will help you....

has_and_belongs_to_many loads wrong resource

ruby-on-rails,ruby,ruby-on-rails-3,activerecord

I found this blogpost http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/ and decided to change HABTM relation to has_many through. After change everything works fine.

undefined method `location' for #

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

This will fail if any of your locations has no events associated with it. You can try to ensure you have no nil elements in your array: @locations = Location.all.includes(:events) @events = @locations.collect{|l| l.events}. flatten. reject{|e| e.nil?} @events.each do |event| puts "event is #{event.inspect}" puts "event location is #{event.location}" end...

undefined method `loan_amount' for nil:NilClass

ruby-on-rails,ruby-on-rails-4,activerecord,foreign-keys,foreign-key-relationship

Your relationship might be returning nil result. Try @jltransaction.jewelloan.try(:loan_amount) ...

Rails find_by - Association comparison

ruby-on-rails,activerecord,associations

SurveySession.joins(:survey).find_by!(id: params[:id], surveys: {user_id: current_user}) ...

Rails 4 - Best way to perform an advanced search

mysql,ruby-on-rails,ruby,activerecord

In you controller do this: class UsersController < ApplicationController def index @users = User.search params[:filter] end end Then in User model do: class User < ActiveRecord::Base def self.search(options = {}) users = User.all users = users.where(name: options[:name] ) if options[:name].present? users = users.where(first_name: options[:first_name] ) if options[:first_name].present? users = users.where(last_name:...

Building a simple calculator form in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,strong-parameters

You should keep in mind that Rails is not only about MVC. You can create your custom classes, and use them in a model, or a controller. In this case, you could create a Calculator class inside app/lib and use it inside your controller. For example: # app/lib/calculator.rb class Calculator...

Ruby destroy is not working? Or objects still present?

ruby-on-rails,ruby,activerecord,destroy

First, let me explain the behaviour with the array preserving destroyed elements. This case is possible due to rails caching mechanism. a.plan_dates.find_by_ddate(Date.today.to_datetime).destroy # DELETE FROM "plan_dates" WHERE ... a.plan_dates.count # SELECT COUNT(*) FROM "plan_dates" WHERE ... a.plan_dates.each { |pd| puts pd.ddate } As you see, the first two rows initiate...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord

I don't think update_attribute is going to be useful as it will replace the array with the new value rather than append to it (but see better explanation below in --Update-- section). I'm not sure what best practices are here, but this should work to just add something if it...

Rails, Postgres, ActiveRecord query postgres based on columns value

ruby-on-rails,ruby,postgresql,activerecord,postgresql-9.3

Event.where.not(repeats: nil) Alternatively, you can specify a sql stream Event.where("repeats is not null") ...

rails query Virtual columns is not exits

ruby-on-rails,activerecord

Its actually present in the ActiveRecord object. You can get it by accessing it as a key of that object: result = User.select("id, (3959 * acos( cos( radians("+latitude+") ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians("+longitude+") ) + sin( radians(" +latitude +") ) *...

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

ruby-on-rails,activerecord

As I said, you need to tweak your create action like this in order to save group_id. def create @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build(discussion_params) @discussion.group_id = @group.id if @discussion.save flash[:success] = "Discussion started." redirect_to root_url end end OR You can add a hidden_field in your form_for to save group_id...

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

php,mysql,activerecord,order,yii2

First you should create ActiveRecord class for video and likes tables to make things easier. The aim is to create the two following classes class Video extends \yii\db\ActiveRecord and class Likes extends \yii\db\ActiveRecord. To do it easily, you should look at gii utility which will do it for you (available...

Codeigniter: Loop in start_transaction

php,codeigniter,activerecord,transactions

It won't effect anything. Suppose your loop has started say from 1 and now reached at position say 15 so the id's inserted in the table would be 1-15 and now some other person added another row and the id moves ahead to 16 and now your continuous loop will...

Rails query through association limited to unique associated objects?

sql,ruby-on-rails-4,activerecord

You may use a subquery: books = Book.where(id: Book.select('MAX(id) AS id').group(:user_id)).order(created_at: :desc) ...

rails has_many at least one children has the value

sql,ruby-on-rails,ruby,ruby-on-rails-4,activerecord

You can use joins method. Group.joins(:users).where("users.mood = ?", User.moods[:good]) You can add this into your migration add_index :users, :group_id ...

Creating a status attribute for a model

ruby-on-rails,ruby,activerecord,model,attributes

Rails 4 has an built in enum macro. It uses a single integer column and maps to a list of keys. class Order enum status: [:ordered, :shipped, :delivered] end The maps the statuses as so: { ordered: 0, shipped: 1, delivered: 2} It also creates scopes and "interrogation methods". order.shipped?...

Trouble in RSpec test - saving parent record twice

ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes

The issue is in sign_up_spec.rb. Your test has a let for user, which means the first time you mention user in your tests it will create a user. However, your application code is supposed to create the user itself. As I said in the comment, this is why in your...

Rails: active record saving time:type with unwanted format

ruby-on-rails,ruby,activerecord,time

Date formats are only valid within your application, not within the database - they are only responsible for the way time objects are displayed to your users and will not affect the way data is stored. Unfortunately, there is no such a concept like time only in the database (at...

Convert MySQL command to ActiveRecord

ruby-on-rails,activerecord

Txaction.where("account_id = 1565 AND recon_status = 2 AND date_posted BETWEEN ? and ?", @date1, @date2).order("date_posted").first ...

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

php,activerecord,orm,yii2

In relation to your remark of having to deal with ORM API, you can use the createCommand approach. You can just use your raw sql query with this method. The difference is that you don't get ActiveRecord[] as a result but just array[] (which is usually fine for complex queries)....

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

ruby-on-rails,ruby,activerecord

Use polymorphic association as follows: # Parameter.rb belongs_to :abc, polymorphic: true # Migration file for parameters t.references :abc, polymorphic: true # Tire.rb has_many :parameters, as: :abc # Rim.rb has_many :parameters, as: :abc Now parameters can be accessed as @tire.parameters or @rim.parameters. ...

rails find records containing specific word [duplicate]

ruby-on-rails,database,activerecord

You can try this search_term = "string" tables = Table.where("tables.content LIKE ?", "%#{search_term}%") or, if you want to ignore case sensitiveness, then do this search_term = "string" tables = Table.where("lower(content) LIKE lower(?)", "%#{search_term}%") Hope this helps!...

ActiveRecord - illegal mix of collations

mysql,ruby-on-rails,ruby,activerecord,character-encoding

Summary I forced a UTF8 collation and converted the data being compared to UTF8 for the actual comparison operation. For some reason, a database trigger I was using (and have been using without issue for 4 months) is the source of the problem. I suspect a change in the database,...

Need to store query result instead of storing query in ActiveRecord

ruby-on-rails,activerecord

You can try this. I hope this will help You. 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)).group_by(&:title) @footer_public_pages[title].first unless @footer_public_pages[title].blank? end ...

No such column for attribute in a join table

ruby-on-rails,activerecord,attributes,associations,jointable

The error is caused by a faulty foreign_key option in TaskVolunteer. belongs_to :volunteer, class_name: "User", foreign_key: :volunteer_id foreign_key here refers to the column on the users table not on tasks_volunteers. You can just remove the foreign key option. class TaskVolunteer < ActiveRecord::Base # task_id, volunteer_id, selected (boolean) belongs_to :task belongs_to...

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

ruby-on-rails,postgresql,ruby-on-rails-4,activerecord

If you're willing to give up selecting all the fields (which you probably don't want anyway, since you're just grouping by product_id), this query will do it for you: OrderItem.group("product_id").sum("unit_price * quantity - line_discount") The result will be a hash, where the keys are product_ids and the values are the...

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

ruby-on-rails,ruby,activerecord

I would create a private method to calculate every piece of: if deadlift_reps != 1 ... end and assign the values to different fields (deadlift, squat, benchpress, overheadpress) using the assign_attributes Active record methods. Here is the code, I didn't test it, but it should work: [["deadlift", 20, 8], ["squat",...

Count from associate table

ruby-on-rails,activerecord,count

You can do the following: @total_user_active = Idee.distinct.count(:user) ...

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

ruby,activerecord,sinatra,em-websocket

I solved it by using a hash. 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: "Invalid Token"}.to_json) unless person return end puts "#{person.name} authenticated!" # person=person.attributes.merge(websock.attributes) # Subscribe...

Updating attributes from check_box

ruby-on-rails,ruby,activerecord

I ended up looking at this Railscast where Ryan Bates shows how to update multiple attributes with fields_for. This is my new view: <%= form_tag quiz_guess_questions_path, :method => :put do %> <% for question in @survey.questions do %> <li><%= question.content %></li> <% for answer in question.answers do %> <li> <%=...

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

ruby-on-rails,ruby,activerecord,padrino

The "all" method doesn't take options. If you're looking to return an array of records with a number of conditions you want to use WHERE. The correct command would be: posts = Post.includes(:account).where(:conditions => condition, :order => "created_at DESC", :limit => postsPerPage, :offset => (page-1)*postsPerPage) For clarity: .all returns every...

Equivalent for SQL WITH RECURSIVE in Arel

sql,ruby,activerecord,arel

After taking a look at the test that @cschroed pointed me to I was able to refactor my raw SQL into: def lineage hierarchy = Arel::Table.new :hierarchy recursive_table = Arel::Table.new(table_name).alias :recursive select_manager = Arel::SelectManager.new(ActiveRecord::Base).freeze non_recursive_term = select_manager.dup.tap do |m| m.from table_name m.project Arel.star m.where arel_table[:id].eq(id) end recursive_term = select_manager.dup.tap do...

Trouble importing multiple CSVs as Rails while maintaining associations

ruby-on-rails,ruby,csv,activerecord

Just assigning the restaurant in memory doesn't update the database. There are two ways to fix this: Save after the assignment: csv.each do |row| inspection = Inspection.create!(row.to_hash.except("permit_id")) inspection.restaurant = Restaurant.find_by(permit_id: row["permit_id"]) inspection.save! end Include restaurant in the create! parameters: csv.each do |row| restaurant = Restaurant.find_by(permit_id: row["permit_id"]) inspection = Inspection.create!( row.to_hash.except("permit_id").merge(restaurant:...

how to set new variable to activerecord object in rails

ruby-on-rails,ruby-on-rails-4,activerecord

what you are looking for is a virtual attribute. Check out this railscast for some more info. An ActiveRecord object is still a ruby object, you can use attr_accessor to add a variable, with setters/getters. class Book < ActiveRecord::Base attr_accessor :new_variable .... end ...

Rails 4 - Create record with has_many through

ruby-on-rails,activerecord

The validation error is actually coming from the Role model, which also has validation for the name attribute. You can do it in one line by creating the website through the role, using accepts_nested_attributes_for: class Role < ActiveRecord::Base validates :name, presence: true belongs_to :user belongs_to :website accepts_nested_attributes_for :website end User.first.roles.create(name:...

Combine logic of boolean value & integer in one activerecord model

ruby-on-rails,ruby,activerecord

You can use existing days_lifetime column and put for example -1 for products with unlimited lifetime(I assume 0 is being used for expired products).

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

Not sure whether it's possible, but it will couple most of your app to the default_scope implementation, which IMHO is a very bad idea. You might end up needing to change this implementation down the line, which is going to have pretty high impact. It will also make your unit...

Update/Delete wrong record because of ActiveRecord “type”

ruby-on-rails,ruby,activerecord

Rails assumes your FooArchive model is using STI (Single Table Inheritance) to instantiate OneFoo objects. You should be able to disable this with: class FooArchive < ActiveRecord::Base self.inheritance_column = nil Note: untested. You may need to use a non-existing column instead of nil to make this work....

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

ruby-on-rails,activerecord

I'm hoping I understand your problem correctly. How about: room.posts.where('id < ?', id).order('created_at desc').limit(20).reverse The reverse at the end simply reverses the order of the results in your query. If this is what you're trying to avoid, I'm not sure how else you'd do it. This seems like a pretty...

how to assign Post to User through user_id and author_id?

ruby-on-rails,activerecord,relationship

Your associations are wrong..they should be like this belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' And now you can call it as @post.author.name There is a difference between belongs_to and has_one and that is you should define belongs_to when that table is containing foreign key....

Chartkick gem, limit group in pie chart and multiple series

sql,ruby-on-rails,activerecord,charts,highcharts

Some heavy thinking and @Agazoom help and I've done this. Code: @top_count = 5 @size = CountChatLine.group(:channel)[email protected]_count @data_top = CountChatLine.group(:channel).order("count_all").reverse_order.limit(@top_count).count @data_other = CountChatLine.group(:channel).order("count_all").limit(@size).count @data_other_final = {"others" => 0} @data_other.each { |name, count| @data_other_final = {"others" => @data_other_final["others"]+count }} @sum_all_data = @data_top.reverse_merge!(@data_other_final) IDK if there is a...

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

ruby-on-rails,activerecord

This: select user_id from UserGroups where group_id = 1; ...is essentially: @group.user_groups.select(:user_id) Methods like this are present in has_many associations. For building subqueries, it seems. So this: select * from Users as u where u.id not in (select user_id from UserGroups where group_id = 1); Is this: User.where.not(id: @group.user_groups.select(:user_id)) The...