iex(6)> :mnesia.table_info(:users, :attributes)
[:id, :email, :foo, :inserted_at, :updated_at]
iex(7)> :mnesia.table_info(:users, :index)
[3]
iex(8)> :mnesia.add_table_index(:users, :email)
{:aborted, {:already_exists, :users, 3}}
I get that Tab is the first index, but then why isn't the index on 2 instead of 3? Are the indexes 1 based instead of zero, or is something else at play here?
Mnesia tables contain tuples that have a record-like format. In your example the tuple that is stored in the :users table looks something like:
{:users, 1, "f#b.com", "foo", {2016, 12, 24}, {2016, 12, 31}}
Which maps to:
Index | 1 | 2 | 3 | 4 | 5 | 6 |
Name | :users | :id | :email | :foo | :inserted_at | :updated_at |
Since tuples are 1-based an index created for the :email value will be created on position 3 of the tuple.
Related
In a Rails ( 4.1.5 / ruby 2.0.0p481 / win64 ) application I have a many-to-many relationship between Student and Course and a join model StudentCourse which represents the association, and has an additional attribute called started (set by default on "false").
I also have added an index in the join-table made of student_id and course_id, and set a unique check on that, like this
t.index [:student_id, :course_id], :unique => true, :name => 'by_student_and_course'
I wanted that to be a composite primary key, but since in rails there are no composite primary keys (without using a gem) I also added a primary key called id:
t.column :id, :primary_key
Now I see that associations are created by either doing:
Student.first.courses.create(:name => "english")
or
Course.first.students << Student.first
This is fine and it's the expected behaviour, I suppose.
That said, I am struggling to wrap my mind around association resolutions in ActiveRecord queries. Let me explain this better:
For reference, Student.all, Course.all and StudentCourses.all would return tables like these:
Student.all
+----+-----------+
| id | name |
+----+-----------+
| 1 | Aidan |
| 2 | Alison |
| 3 | Elizabeth |
+----+-----------+
Course.all
+----+----------+------------------+
| id | name | description |
+----+----------+------------------+
| 1 | english | desc. here |
| 2 | music | desc. here |
| 3 | dance | desc. here |
| 4 | science | desc. here |
| 5 | french | desc. here |
| 6 | arts | desc. here |
+----+----------+------------------+
StudentCourse.all
+-------------+------------+------------+----+
| course_id | student_id | started | id |
+-------------+------------+------------+----+
| 1 | 1 | false | 1 |
| 2 | 1 | false | 2 |
| 3 | 1 | false | 3 |
| 1 | 2 | true | 4 |
| 2 | 2 | true | 5 |
| 4 | 3 | false | 6 |
| 5 | 2 | false | 7 |
| 5 | 1 | true | 8 |
| 6 | 2 | false | 9 |
+-------------+------------+------------+----+
So far I can happily render a json object of all courses, and names of all students for each course like this:
render json: Course.all.to_json(:include => {:students => {:only => :name}})
I can also easily render all courses that a student is attending or about to attend with
render json: #student.courses.to_json(:include => {:students => {:only => :name}})
which also includes other students for those courses.
But suppose I wanted to render one student's courses which the student has not yet started, together with all the other students who are on that course (which have or not started the course) [Please read the UPDATE section below, I'm looking for the opposite thing actually!]
I think the easieast approach is to query the join-table for something like:
StudentCourse.all.where(student_id: #student.id, started: false)
+-------------+------------+------------+----+
| course_id | student_id | started | id |
+-------------+------------+------------+----+
| 5 | 2 | false | 7 |
| 6 | 2 | false | 9 |
+-------------+------------+------------+----+
But how do I go on from this resulting table (association object) to get a nicely packaged json object with courses names (and all other attributes) and also including students in it, like I did with: Course.all.to_json(:include => {:students => {:only => :name}}) ?
I think I'm missing some basic knowledge of some important key concepts here, but at this point I cannot even indentify them and would greatly appreciate some help... thank you.
Update:
I just realized that the following part is what I was originally trying to do. It's the opposite thing. Among all these details I got lost along the path. I hope that it's ok if I just add it here.
So, given a student (let's call him Aiden), I need to return a JSON object containing only the courses that he is in and that he has started, only when such courses have other students in them who have not started them, and it has to include the names of those students for each course too.
So...
I now have:
aiden_started_courses = Student(1).courses.where(:student_courses => {:started => true } )
which for a student takes all the courses that have a "true" value in the join-table "started" column. (again in the join table each student-course record is "compositely" unique, so there can just be one unique record for a given student_id and course_id).
With the next query, for one of "aiden_started_courses" I can pull off all the relative student-courses associations which have a false value on "started"
aiden_started_courses[0].student_courses.where(:started => false).includes(:student).to_json(:include => :student)
+-------------+------------+------------+----+
| course_id | student_id | started | id |
+-------------+------------+------------+----+
| 1 | 2 | false | 4 |
+-------------+------------+------------+----+
| 1 | 9 | false | 5 |
+-------------+------------+------------+----+
So here lies the problem: I have managed to get this just for a single course in aiden_started_courses array, but how would I be able to build a query that returns this data for all of Aiden's started courses?
Is it possible to do that in one line? I know I could probably use Ruby enumerator loops but I somewhat feel that I would be kind of breaking some pattern both on a Rails coding convention level and on performance level? (hitting N+1 problem again?) ...
What I could so far:
I came up with this where I find all students who have not started the courses which a given user has started:
Student.includes(:student_courses).
where(:student_courses => { :started => false, :course_id => aiden.courses.where
(:student_courses => {started: true}).ids } )
or this:
Course.includes(:students).where(:student_courses => {:started => false,
:course_id => aiden.courses.where(:student_courses => {:started =>true}).ids })
which finds all the courses that a given student has started if those courses include students who have not started them yet
But what I really need is to get a JSON object like this:
[
{
"id": 1,
"name": "english",
"students": [
{"name": "ALison"},
{"name": "Robert"}]
},
{
"id": 2,
"name": "music",
"description": null,
"students": [
{"name": "Robert"},
{"name": "Kate"}]
}
]
where I can see the courses that a given student is on and has started, but only those in which there are other students that have not yet started it, together with the names of those students...
I'm thinking that probably there is no way how I could get that through a regular AR query, so maybe should a build a JSON manually? But how could I do that?
Thanks in adv. and I apologise for the verbosity.. but hopefully it will help..
Use scope to your advantage:
class Course < ActiveRecord::Base
# ...
scope :not_started, -> { joins(:student_courses) \
.where(student_courses: {started: false}) }
scope :with_classmates, -> { includes(:students) } # use eager loading
end
Then call:
#student.courses.not_started.with_classmates \
.to_json(include: {students: {only: :name}})
Output:
[
{
"id": 1,
"name": "english",
"description": null,
"students": [
{"name": "Aiden"},
{"name": "Alison"}]},
{
"id": 2,
"name": "music",
"description": null,
"students": [
{"name": "Aiden"},
{"name": "Alison"}]},
{
"id": 3,
"name": "dance",
"description": null,
"students": [
{"name": "Aiden"}]}]
Use JBuilder, it comes by default with Rails. Ignore the lines starting with '#':
Jbuilder.new do |j|
# courses: [{
j.courses <student.courses - replace this with whatever variable> do |course|
# id: <course.id>
j.id course.id
# name: <course.name>
j.name course.name
# students: [{
j.students <course.students - replace with whatever variable> do |student|
# name: <student.name>
j.name student.name
end
# }]
end
# }]
end
Not a lot of code. Removing the comments and simplifying some features, it will look like:
student_courses = <...blah...>
json = Jbuilder.new do |j|
j.courses student_courses do |course|
j.(course, :id, :name)
j.students <course.students - whatever method here>, :name
end
end.target!
Check out their guide, its pretty awesome to generate JSON in plain Ruby DSL. So go ahead and use whatever ruby code you want to fetch students/courses/studentcourses.
The goal
Count entries on association table and inject it into a model, using Rails (v. 4.1).
The scenario
There is game.rb model:
class Game < ActiveRecord::Base
has_and_belongs_to_many :genres
end
and there is also a genre.rb model:
class Genre < ActiveRecord::Base
end
In the database, there are three tables: games, genres, games_genres – and games is still empty because I'm still developing genres area. So, genres' table is like following:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Action |
| 2 | RPG |
+----+-----------+
And this is games_genres table:
+----+--- -----+----------+
| id | game_id | genre_id |
+----+---------+----------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
+----+---------+----------+
The problem
My application has an API and to retreive genres, I'm doing this way:
class API::V1::TargetsController < ApplicationController
def index
render json: Genre.all.to_json
end
end
The output is something like this:
[
{
id: 1,
name: 'Action'
},
{
id: 2,
name: 'RPG'
}
]
But, I want to inject the count of how many products has each genre. The query is simple:
SELECT COUNT(genre_id) AS products_quantity FROM game_genres
So, how can I inject products_quantity see above's query within Genre model? Something to get the JSON's output like this:
[
{
id: 1,
name: 'Action',
products_quantity: 2
},
{
id: 2,
name: 'RPG',
products_quantity: 1
}
]
You can add a method option to the to_json method. Thus you can define a product_quantity method on your Genre model
def product_quantity
game_genres.count
end
and then have it included in the to_json call.
class API::V1::TargetsController < ApplicationController
def index
render json: Genre.all.to_json(methods: :product_quantity)
end
end
While the above will work, I would suggest you use something more robust like rabl to handle JSON responses.
In default AwesomeNestedSet gem is sorting by :lft attribute. Suppose I have a class:
class Category < ActiveRecord::Base
acts_as_nested_set
attr_accessible :name, :position, :parent_id, :lft, :rgt
end
How can I create a sortable (by :position attribute) tree with AwesomeNestedSet gem with one hit to the database where :position is used for sorting siblings (level)?
I need output something like this:
----------------------------------
id |position | name | parent_id |
----------------------------------
1 | 1 | item1 | nil |
----------------------------------
2 | 1 | item11 | 1 |
----------------------------------
3 | 1 | item111| 2 |
----------------------------------
4 | 2 | item12 | 1 |
----------------------------------
5 | 2 | item2 | nil |
----------------------------------
I have a model:
class Row < ActiveRecord::Base
belongs_to :description
attr_accesible :id, :q_id, :quantity, description_id
end
class Description < ActiveRecord::Base
has_many :rows
translate :description #globalize3, ignore it.
attr_accesible :id, :other
end
In this case, Description and Row have a 1:N relationship (N from 1 to 3).
What is the best way to show this in table format in Haml? For example if we have in the DB:
Row:
1 | 1 | 20 | 1
2 | 2 | 22 | 1
3 | 1 | 30 | 2
4 | 3 | 31 | 2
5 | 2 | 32 | 2
Description:
1 | asd
2 | zxc
I would like to show this form:
desc | q1 | q2 | q3 |
-----+----+----+----+
asd | 20 | 22 | -- |
zxc | 30 | 32 | 31 |
UPDATE
I added a new attribute (q_id) that indicates the "q" position (1, 2, or 3) to my Row model.
In your controller code:
#descriptions = Description.eager_load(:rows).order('descriptions.id, rows.q_id')
In your view:
%table
%tr
%th= 'desc'
%th= 'q1'
%th= 'q2'
%th= 'q3'
- #descriptions.each do |description|
%tr
%td= description.description
- (0..2).each do |i|
%td= description.rows[i].try(:quantity) || '--'
UPDATE
If you want to limit the rows to a specific user association, you can do so like this:
#descriptions = Description.eager_load(:rows).
where(rows: {user_id: some_user.id}).
order('descriptions.id, rows.q_id')
If you are concerned that this may exclude a description that has no matching rows, you can substitute a SQL fragment with a NULL alternative:
#descriptions = Description.eager_load(:rows).
where('rows.user_id = ? OR rows.id IS NULL', some_user.id).
order('descriptions.id, rows.q_id')
Something like:
%table
%tr
- Description.includes(:rows).find_each do |description|
%td= description.description
%td= format_quantity description.rows.first
%td= format_quantity description.rows.second
%td= format_quantity description.rows.third
And a helper function
def format_quantity(row)
row.present? ? row.quantity : '--'
end
UPDATE
For the order of rows, you could specify that on your relation
class Description < ActiveRecord::Base
has_many :rows, order: 'q_id'
There is a table with fields: id, name, id_cat
Please show an example of a method that outputs these categories. And where you want to implement this method in the controller or in helpers? Help implement this recursive method.
As I correctly understand you have Category table with circular reference realised by column id_cat.
Following model should works as you expected:
class Category < ActiveRecord::Base
belongs_to :supercategory, :class_name => "Category", :foreign_key => "cat_id"
has_many :subcategories, :class_name => "Category", :foreign_key => "cat_id"
end
So if categories table looks like:
id | name | cat_id
---------------------------
1 | cat 1 | null
2 | cat 1.1 | 1
3 | cat 1.2 | 1
4 | cat 2 | null
5 | cat 1.2.1 | 3
Category.find(1).subcategories returns array with cat 1.1 and cat 1.2 objects.
Category.find(1).supercategory returns nil
Category.find(3).supercategory returns cat 1 object
Category.find(4).supercategory returns nil
...