ruby-on-rails,ruby,activerecord
The bullet gem can be used to log n+1 queries. It works pretty well for me.
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 } ...
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...
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.
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 ...
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...
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 ...
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:...
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)
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,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...
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.
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...
sql,ruby-on-rails,postgresql,activerecord
Underscore is a wild card in sql, so try 'above_the_line'.
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...
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 ...
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...
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,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
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....
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 ...
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...
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") ...
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...
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....
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 ...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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) ...
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....
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...
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...
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...
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...
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...
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...
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
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...
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,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") ...
ruby-on-rails,postgresql,activerecord,jsonb
You should call this as below : Person.where("roles ? :name", name: "32486d83-4a38-42ba-afdb-f77ca40ea1fc") ...
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....
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.
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...
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) ...
ruby-on-rails,activerecord,associations
SurveySession.joins(:survey).find_by!(id: params[:id], surveys: {user_id: current_user}) ...
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:...
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-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...
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...
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") ...
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 +") ) *...
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...
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...
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...
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) ...
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 ...
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?...
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...
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...
Txaction.where("account_id = 1565 AND recon_status = 2 AND date_posted BETWEEN ? and ?", @date1, @date2).order("date_posted").first ...
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)....
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. ...
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!...
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,...
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 ...
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...
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...
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",...
ruby-on-rails,activerecord,count
You can do the following: @total_user_active = Idee.distinct.count(:user) ...
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...
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> <%=...
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...
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...
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:...
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 ...
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:...
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).
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...
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....
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...
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....
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...
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...