logo
down
shadow

Rails: Group By join table


Rails: Group By join table

Content Index :

Rails: Group By join table
Tag : ruby-on-rails , By : Guid
Date : December 05 2020, 12:18 PM

seems to work fine If your only goal is to get the task counts per workspace, I think you want a different query.
@workspaces_with_task_counts = 
  Workspace
    .joins(:projects)
    .joins(:tasks)
    .select('workspaces.name, count(tasks.id) as task_count')
    .group(:workspace_id)
@workspaces_with_task_counts.each do |workspace|
  puts "#{workspace.name}: #{workspace.task_count}"
end
Workspace
  .joins(projects: { tasks: :urgencies })
  .where(urgencies: {urgency_value: 7})
  .group(:name)
  .count
{"workspace1"=>4, "workspace2"=>1}
Task
  .joins(project: :workspace)
  .includes(project: :workspace)
  .group_by { |task| task.project.workspace.name }
{
  "workspace1": [task, task, task],
  "workspace2": [task, task],
  "workspace3": [task, task, task, task]
}
tasks = Task.joins(project: :workspace).includes(project: :workspace)
counts = tasks.group('workspaces.name').count
{ "workspace1": 3, "workspace2": 2, "workspace3": 4 }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How do I group by and order by count in Rails through a join table?


Tag : sql , By : pad
Date : March 29 2020, 07:55 AM
may help you . How do I translate this SQL into Rails? , Try:
Posts.first.tags.select("tags.tag, count(1) as tag_count").group('tags.tag').order('tag_count desc')

Rails 4 OR query with join table using group and having


Tag : sql , By : waarg
Date : March 29 2020, 07:55 AM
wish helps you ActiveRecord cannot do or but Arel can. The amazing scuttle.io will solve your problem:
Position.select(Position.arel_table[Arel.star]).where(
  Position.arel_table[:user_id].eq(4).or(
    Position.arel_table[:active].eq(0).or(Position.arel_table[:deadline].lt('2015-01-21')).or(Cv.arel_table[:accepted].eq(1))
  )
).joins(
  Position.arel_table.join(Cv.arel_table).on(
    Cv.arel_table[:position_id].eq(Position.arel_table[:id])
  ).join_sources
).group(:id)

JOIN Many table while GROUP BY and COUNT the GROUP BY row in MySQL


Tag : php , By : Valentine
Date : March 29 2020, 07:55 AM
hop of those help? I think this problem is easier to solve with PHP.
Use your query and fetch your data into an associative array. I should look like this:
$dbData = [
    ['id_lpkon' => 1, 'id_lpseb' => 1,    'id_lprek' => 1,    'id_lptl'  => 1],
    ['id_lpkon' => 1, 'id_lpseb' => 1,    'id_lprek' => 1,    'id_lptl'  => 2],
    ['id_lpkon' => 1, 'id_lpseb' => 1,    'id_lprek' => 2,    'id_lptl'  => null],
    ['id_lpkon' => 1, 'id_lpseb' => 2,    'id_lprek' => null, 'id_lptl'  => null,],
    ['id_lpkon' => 2, 'id_lpseb' => null, 'id_lprek' => null, 'id_lptl'  => null,]
];
$columns = ['id_lpkon', 'id_lpseb', 'id_lprek', 'id_lptl'];
$counts = [];
foreach ($columns as $column) {
    $counts[$column] = [];
}

foreach ($dbData as $row) {
    foreach ($row as $column => $value) {
        if ($value === null) {
            continue;
        } elseif (isset($counts[$column][$value])) {
            $counts[$column][$value]++;
        } else {
            $counts[$column][$value] = 1;
        }
    }
}
$counts = [
  'id_lpkon' => [1 => 4, 2 => 1],
  'id_lpseb' => [1 => 3, 2 => 1],
  'id_lprek' => [1 => 2, 2 => 1],
  'id_lptl'  => [1 => 1, 2 => 1],
];
foreach ($dbData as $rn => $row) {
    foreach ($row as $column => $value) {
        $countColumn = $column . '_count';
        if ($value === null) {
            $dbData[$rn][$countColumn] = null;
        } else {
            $dbData[$rn][$countColumn] = $counts[$column][$value];
        }
    }
}

LINQ: How can I Join to child table using data from group join?


Tag : vb.net , By : Will
Date : March 29 2020, 07:55 AM
wish helps you Assuming the TitleSearchResult has List types for Old_Titles and Transactions, you can do:
var ans =  From t In query3.ToList() _
           Select New TitleSearchResult() With {
               .Title = t.title,
               .Pc_Parcel = t.parcel,
               .Transactions = t.transactions.Select(Function(t1) t1.trans).ToList(),
               .Old_Titles = t.transactions.Select(Function(t1) t1.title_old).ToList()
           }

Retireve max/min row with left join trick for a group, when group is on another table


Tag : mysql , By : user98832
Date : March 29 2020, 07:55 AM
Does that help What you need to do to make this work is to LEFT JOIN the JOIN of the two tables to each other:
SELECT p1.*, m1.*, m2.*
FROM (messparent p1 JOIN messages m1 ON p1.fk_mess = m1.id)
LEFT JOIN
(messparent p2 JOIN messages m2 ON p2.fk_mess = m2.id)
ON m2.when > m1.when AND p2.grp = p1.grp
WHERE m2.id IS NULL
grp fk_mess id  when        id  when
1   3       3   2000-08-16  (null)  (null)
2   6       6   2000-08-19  (null)  (null)
Related Posts Related QUESTIONS :
  • Skip Current Migrations but Apply Future Ones
  • How to handle data with two has_many associations
  • Show SQL ActiveRecord queries in rails console using SemanticLogger gem
  • Custom strategy for Omniauth
  • How to obtain constant memory usage when migrating a Rails application from mongoid (MongoDB) to ActiveRecord (Postgres)
  • how do i redirect to home page(root )when user signed out?
  • Ruby two strings in an IF condition
  • Nginx passenger integration mode always require Passengerfile.json file?
  • what class is returned after a delete action in rails
  • Convert an array of hash with symbols
  • How can i display a particular product?
  • Rails remove subarray from array
  • Ruby : How to record an object and reuse it for tests?
  • Rails multiple select on array attribute not working
  • How use local views built with gem devise in rails app?
  • Deploying Rails App on Digital Ocean and when running cap production deploy:initial I get back ---> 01 ArgumentError:
  • How do I seed data of a class which requires the user_id of the current user?
  • How to do an RSpec oneliner to test a :count change
  • Rails 5 left_outer_join with specific saved ID
  • Rails: devise_invitable not accepting variables
  • How to spy on a method called at class level on ActiveRecord model?
  • Azure AD authentication with Rails and devise
  • Avoiding n+1 has_many children should remember parent
  • Ruby/Rails How to parse datetime from russian string
  • How to remove substring that may appear within a string?
  • param is missing or the value is empty: But parameter IS there with a value
  • What is cost/benefit of object.models.find() vs Model.find() in Ruby on Rails (Mongoid)
  • User is getting session from other logged in user with Rails / Devise
  • How to run docker compose up for production environment
  • In Rails 5 where should I put my javascript_include_tag?
  • Rubocop -> Use a guard clause
  • How does assigns know where to look for the instance variable in integration tests?
  • Rails 5.2.3 converting all params datatype to string when testing using rspec
  • RegEx for client-side server in Ruby on Rails
  • Aws CostExplorer Api giving exception using ruby sdk
  • rails webpack compilation hangs in production at 78% [0] chunk asset optimization TerserPlugin
  • How to remove an object from the ActiveRecord::Relation object
  • Where does http protocol rests in rails framework?
  • What is the shortest way to write condition variable in rails view template?
  • Find source location of an aliased method
  • ES6 syntax, harmony mode must be enabled with Uglifier.new(:harmony => true
  • Capybara can't find element if JS is present
  • Enviornment broken after uninstalling Rails 6.0.0.rc1
  • How to get current user in Rails model
  • Convert simple text into html honoring newlines whitespaces and tabs
  • How to Parse LARGE JSON files with formating error
  • Rails + Vue.js - Using Ajax to update Vue component
  • Has_many association with specific values: how-to?
  • How to fix 'warning: constant ::Fixnum is deprecated' error
  • Should I use helper method for this method?
  • How to check user's role after login in Rails?
  • Convert [object Object] to JSON
  • Ruby on Rails: attr_accessor for submodels
  • Storing multiple checkbox values in database
  • STI and polymorphs
  • Get Mechanize to handle cookies from an arbitrary POST (to log into a website programmatically)
  • link_to not working in script/console
  • How to change color of HAML tags in NetBeans?
  • ruby super keyword
  • Ruby number_to_currency displays a totally wrong number!
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com