ActiveRecord has_one and has_many relation with the same :foreign_key - ruby

I have two models, Story and Chapter. A story has_many chapters, one of those is a chapter which serves as its first chapter. I used to have a foreign key start_id in the stories table to indicate which chapter is the first. Hovewer, the the database schema had to be changed a little, now every chapter has a code. If the code is '1a', then that is first chapter of the story which owns the chapter.
The following seems to work, including #create_start:
has_many :chapters, :dependent => :destroy, :inverse_of => :story
has_one :start, :class_name => 'Chapter', :foreign_key => 'story_id', :conditions => {:code => '1a'}
This way, the foreign key start_id of the stories table is unneeded, and #start still remains an association, with all the benefits (I need #start as an association, because I use CanCan with associations for authorization).
Does my approach has any drawbacks that I currently fail to realize, or I am relatively safe with it?

Relying on the code == '1a' to find the first chapter is a bit wonky. I'd probably add a flag to the chapters table like 'first_chapter' or something that was true or false indicating whether it was the first chapter. This way the first_chapter-ness of a chapter would survive a change to the code field, but this is a bit nitpicky.
Also, to avoid repeating yourself, you could change the declaration of has_one :start to something like:
has_one :start, :through => :chapters, :conditions => { :code => '1a' }

Related

database schema for like entities that can be combined pairwise (ActiveRecord)

I am designing a database of woodwind instrument sounds, and would like to create a table that joins pairs of sounds that a performer can combine into, for example, a trill. Such relations are transitive: if sound A has a 'Sound Relation' with sound B, then sound B has that same 'Sound Relation' with sound A.
I am familiar with join tables, but I've never seen them used to join 'like' objects, only to join 'unlike' objects, such as tags and posts, so I'm wary of going that direction.
I realize the example below looks extremely dubious, but it gives an idea of what I'm after. What is a better way of doing it? (Using ActiveRecord syntax)
Models
class Sound < ActiveRecord::Base
has_many :linked_sounds, through: :sound_relations, class_name: "Sound", foreign_key: ???
end
class Sound_Relation < ActiveRecord::Base
has_many :sounds
end
Migration
class CreateSoundRelations < ActiveRecord::Migration
def change
create_table :sound_relations do |t|
t.integer first_sound_id # This cannot possibly be right.
t.integer second_sound_id # Surely the transitivity of the
# relationship should be more evident?
end
end
end
You might try something like:
class Set < ActiveRecord::Base
has_many :sound_sets
has_many :sounds, :through => :sound_sets
end
class SoundSet < ActiveRecord::Base
belongs_to :sound
belongs_to :set
end
class Sound < ActiveRecord::Base
has_many :sound_sets
has_many :sets , :through => :sound_sets
has_many :set_sound_sets, :through => :sets , :source => :sound_sets
has_many :set_sounds , :through => :set_sound_sets, :source => :sound
end
So, no more "sound_1" and "sound_2" ... they are both just sounds. For every sound you can also use the set_sounds method to retrieve all of the sounds associated with it.
This would also allow more than two sounds in a relation, and you might like to put a "type" on the sets model.
Edit: If you look at the query generated, you'll find that sound_sets is mentioned in there twice, once with a different alias. The key to eliminating "self" joins is to include a clause in the association along the lines of:
has_many :set_sounds ,
{where("sound_sets.sound_id != set_sound_sets_sound_set_sounds.sound_id")},
:through => :set_sound_sets,
:source => :sound
... where "sound_set_sounds" is the table alias. If you can post the query in the comments I can update this with the actual alias.

Querying and sorting embedded document in mongoid

I have three classes
class Post
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user, :inverse_of => nil
embeds_many :comments, :as => :commentable
field :content, :type => String
end
class Commment
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user, :inverse_of => nil
embedded_in :commentable, :polymoriphic => true
end
class User
has_many :posts, :dependent => :destroy
field :name, :type => String
end
Whenever the user creates a new comment, I want to compare the contents of it with the latest comment that the user has made. Here is my code that fetches the latest comment by the user:
comments_user=[]
Post.where("comments.user_id" => user.id).
only(:comments).
each {|p| comments_user += p.comments.where(:user_id => user.id).to_a}
latest_comment = comments_user.sort_by{|comment| comment[:updated_at]}.reverse.first
The above code gives me the result but the approach taken is not efficient as I have to traverse through all the posts that the user has commmented to find the latest comment. If any, can anyone provide me a more efficient solution to this problem?
Simply speaking, Isn't there any way I can get all the comments made by this user?
This should fetch the latest user`s comment:
Post.where("comments.user_id" => user.id).order_by(:'comments.updated_at'.desc).limit(1).only(:comments).first
This is standard problem with embedding. It greatly improves some queries ("load post with all its comments"), but makes others non-efficient/impractical ("find latest comment of a user").
I see two options here:
Keep embedding and duplicate data. That is, when user makes a comment, embed this comment to a post document and to the user document. This data duplication has its drawbacks, of course (what if you need to edit comments?);
Stop embedding and start referencing. This means that comment is now a top level entity. You can't quickly load a post with comments, because there are no joins. But other queries are faster now, and there's no data duplication.

Why doesn't my associations go both ways in ActiveRecord?

So I'm connecting to a legacy database. I have two tables, Sites and States.
A Site has one State and a State can belong to many Sites
# Sites.rb
has_one :state, :primary_key => "StateKey", :foreign_key => "StateKey"
# States.rb
belongs_to :sites, :class_name => "Sites", :primary_key => "SiteKey", :foreign_key => "SiteKey"
As you can see I have to manually set the foreign keys and primary keys.
So this works:
Sites.first.state # one record returned (the state)
This does not:
States.first.sites # nil returned. Doesn't even appear to hit AR
What am I doing wrong?
Thanks.
You should use the pair has_many, belongs_to:
# Sites.rb
belongs_to :state, :primary_key => "StateKey", :foreign_key => "StateKey"
# States.rb
has_many :sites, :class_name => "Sites", :primary_key => "StateKey", :foreign_key => "StateKey"
Take a look at this guide.
When you have a one-to-many association it is standard practice to use belongs_to and has_many in the two model classes. has_one is a special case of has_many. belongs_to says that the foreign key is in the model declaring the association, and has_one, has_many say the foreign key is in the other model.

MongoMapper: how do I create a model like this

Suppose we have two models, Task and User.
So a user can have many tasks and tasks should be able to have many users too. But, a task should also have a unique creator who is also a user.
Exemple:
A task in this context is like this:
Task ID, Task Creator, Users who should do the task
User_1 creates a task and he is then the creator.
User_1 specifies User_2 and User_3 as users who should do the task. So these two last users are not creators of task.
How do I create this models so that if I have a task object, I can find it's creator and users who should complete it. And how do I do, if I have a user, to find all tasks he created and all tasks he should complete.
You'll need a many-to-many relationship between the Tasks and Users, and you need an additional one-to-many relationship between Users and Tasks, pointing to the creator (User).
Something along these lines: (I usually use Mongoid, so double-check the syntax for the relations in the MongoMapper API - link below.. you might to manually specify :foreign_key and :class)
The idea is that you have two relationships between the models, one which models the many-to-many relationship
with which you get either to the assigned_users or assigned_tasks, and a one-to-many relationship with which you get to either the creator of a task, or the created_tasks for a given user. If you chose these names for the relationships, it will be clear which is which.
class Task
include MongoMapper::Document
key :title, String , :required => true
key :user_ids , Array
has_many :users, :in => user_ids # , :as => :assigned_users
key :creator_id , ObjectId
belongs_to: user, :as => :creator
end
class User
include MongoMapper::Document
key: name, String, :required => true
has_many :tasks # , :as => :assigned_tasks
has_many :tasks, :as => :created_tasks
end
See:
http://mongomapper.com/documentation/plugins/associations.html
The answer suggested by Tilo is correct about how to model the data, but the example code is incorrect and will not work. The :as option is for polymorphic associations, you want to use the :foreign_key option. Also, you can't have two associations named the same. See below for revised code.
class Task
include MongoMapper::Document
key :title, String , :required => true
key :assigned_user_ids, Array
has_many :assigned_users, :in => :assigned_user_ids
key :creator_id , ObjectId
belongs_to :creator, :class => User
# userstamps! also accomplishes the above
end
class User
include MongoMapper::Document
key: name, String, :required => true
has_many :created_tasks, :foreign_key => :creator_id, :class => Task
# inverse of many :in is still in the works
# see https://github.com/jnunemaker/mongomapper/pull/259
# this is a decent workaround for now
def assigned_tasks
Task.where(:assigned_user_ids => self.id)
end
end
See also:
MongoMapper userstamps! documentation

Rails 3.1 has_many, :through => not working (joined model returns nil)

Update: This was all due to a stupid error: previously, I had defined a method with the same name as one of the methods ActiveRecord creates, which was masking the proper behaviour and breaking everything. I can't answer/close the question for a few more hours, apologies to anyone who looked into this!
I have an infuriating problem with a has_many, :through => relationship in my Rails 3.1 app.
It is infuriating because as far as I can see it is identical to two similar relationships which both work.
The owner of these relationships declares them like this:
has_many :user_skills, :dependent => :destroy
has_many :skills, :through => :user_skills
has_many :user_roles, :dependent => :destroy
has_many :roles, :through => :user_roles
has_many :conversation_users
has_many :conversations, :through => :conversation_users
(I am aware I have not followed standard nomenclature for join tables here - I only read about the convention of both-plural, names-alphabetical after setting this up, and I will refactor later)
The first two pairs of relationships (skills and roles) work just fine.
The final relationship (conversations) does not work fully. user.conversation_users returns the expected array, but user.conversations returns nil. Not an empty array, nil.
I may well be doing something stupid here, so I would be very grateful to anyone who can spot something wrong with the ConversationUser or Conversation models below.
conversation_user.rb
class ConversationUser < ActiveRecord::Base
belongs_to :user, :inverse_of => :conversation_users
belongs_to :conversation, :inverse_of => :conversation_users
validates_presence_of :user
validates_presence_of :conversation
end
conversation.rb
class Conversation < ActiveRecord::Base
has_many :messages, :dependent => :destroy
has_many :conversation_users, :dependent => :destroy
has_many :users, :through => :conversation_users
validates_presence_of :unique_id
end
(I am also aware that these are not really complex enough to justify has_many, :through => over has_and_belongs_to_many, but planned additional functionality will require join models.)
Answering to close question:
This was all due to a stupid error: previously, I had defined a method with the same name as one of the methods ActiveRecord creates, which was masking the proper behaviour and breaking everything.

Resources