Making ActiveRecord join model attributes available in query results - ruby-on-rails

Given User and Book models, I've created a join model, ViewedBook, that contains additional attributes. Below is the essence of what I've come up with:
create_table "users"
t.string "username"
end
create_table "books"
t.string "title"
t.integer "user_id"
t.date "authored_date"
end
create_table "books_viewings"
t.integer "book_id"
t.integer "user_id"
t.boolean "finished"
t.date "last_viewed_date"
end
class User
belongs_to :book_viewing
has_many :authored_books,
:class_name => "Book",
:source => :book
has_many :book_viewings
has_many :viewed_books :through => :book_viewings
:order => "book_viewings.last_viewed_date DESC"
has_many :finished_books :through => :book_viewings
:conditions => "book_viewings.finished = TRUE",
:order => "book_viewings.last_viewed_date DESC"
end
class Book
belongs_to :user
has_one :author, :class_name => "User"
end
class BookViewing
belongs_to :book
belongs_to :user
end
I think this works for most of the queries I need to create. However, I want each of the Book objects returned by user.viewed_books to include the finished attribute as well. Further, I will have additional queries like Book.best_sellers that I would also like to scope to a given user so that they also include the finished attribute.
From my limited exposure to ActiveRecord, it appears there's probably an elegant way to manage this and generate efficient queries, but I have yet to find an example that clarifies this scenario.
EDIT: to clarify, the other queries I'm looking for will not themselves be restricted to books that have been finished, but I need to have the finished attribute appended to each book if it exists for the given book and scoped user in book_viewings.

See my answer here https://stackoverflow.com/a/8874831/365865
Pretty much, no there isn't a specific way to do this, but you can pass a select option to your has_many association. In your case I'd do this:
has_many :books, :through => :book_viewings, :select => 'books.*, book_viewings.finished as finished'

Related

Association with same model

I have a City model which I would like to set up an optional relationship with another city known as a sister city. In order to avoid adding another column to cities I would like to create a join table that holds the association.
create_table :sister_city_mappings do |t|
t.integer :city_id
t.integer :sister_city_id
t.timestamps null: false
end
class City
has_one :sister_city_mapping, :class_name => 'SisterCityMapping',
foreign_key: :city_id
has_one :sister_city, :class_name => 'City', through:
:sister_city_mapping, source: :sister_city
end
class SisterCityMapping
belongs_to :city, :class_name => 'City'
belongs_to :sister_city, :class_name => 'City',
foreign_key: :sister_city_id
end
This kind of works as I can do City.first.sister_city = City.last but I can not handle the relationship through form params as cleanly as I'd like:
City.first.sister_city_id = 2
NoMethodError: undefined method `sister_city_id=' for #<City:0x007f893be1b178>
and trying:
City.first.sister_city = 2
ActiveRecord::AssociationTypeMismatch: City(#70113697769780) expected, got Fixnum(#70113638622260)
I think it's very likely that the associations are incorrect, I have also tried SisterCityMapping has_one :sister_city but haven't been successful.
You really should just add a sister_city_id column to your cities table:
class City
has_one :sister_city, :class_name => 'City'
end
If you really want to use this join table association, you can create the relation like this:
City.first.sister_city = City.find(2)

ActiveRecord double belongs_to doesn't include the foreign relation

In Rails 3.2, I have a dictionary with words and references, named "gotowords" which store the word they belong to in word_id and the word they make reference to in reference_id (ie. gotofrom in the models):
create_table "words", :force => true do |t|
t.string "word"
t.text "definition"
end
create_table "gotowords", :force => true do |t|
t.integer "word_id"
t.integer "reference_id"
end
With the models:
class Word < ActiveRecord::Base
has_many :gotowords
has_many :gotofroms, class_name: "Gotoword", foreign_key: "reference_id"
end
class Gotoword < ActiveRecord::Base
belongs_to :word
belongs_to :gotofrom, class_name: "Word", foreign_key: "id"
end
The following query works, but makes another query for each gotofroms.word which is apparently not included:
#words = Word.includes(:gotowords, :gotofroms)
I cannot (for now) refactor like this answer suggests, as the application is pretty huge and it would have too many consequences. That said, I can live with the supplemental query, but it bugs me... Adding inverse_of as is doesn't solve the problem:
has_many :gotowords, inverse_of: :word
has_many :gotofroms, class_name: "Gotoword", foreign_key: "reference_id", inverse_of: :gotofrom
Is there a solution to include Word twice in that configuration?
Try using preload. It works a bit different, but might still help to eliminate duplicated db queries:
#words = Word.preload(:gotowords, :gotofroms)

Inbox messages in rails like facebook

I am trying to create a personal inbox message system but couple question are on my mind. First let me explain my system.
Here is my table model
create_table "inboxmessages", :force => true do |t|
t.integer "receiver_id"
t.integer "sender_id"
t.integer "message_id"
t.boolean "isread"
t.boolean "isstarred"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "messages", :force => true do |t|
t.string "subject"
t.text "body"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
The relationship would be has follow
inboxmessages
belongs_to :message
belongs_to :user, :class_name => "User", :foreign_key => "sender_id"
belongs_to :user, :class_name => "User", :foreign_key => "receiver_id"
messages
has_many :inboxmessages
user
has_many :inboxmessages
The problem that i am having his i am uncertain on how to create a message which allows me multiple users. here the schema of the form i am trying to have
Message.subject
Inboxmessage.receiver # but have multiple different user
------------------------------------------------------------------------
Message.body
Inboxmessage.sender = current_user # hidden field
Here are the question that I have regarding building this model/controller/app
1 - Should my new form be in inboxmessages or messages?
2 - Should I use accept_nested_for or should I use nested resources
3 - Is my model/database is okay or not the best?
4 - Are my foreign_key relationship well define?
Thanks in advance!!
I would do something like this:
class User
has_many :mailboxes
has_many :messages, :through => :tags
has_many :tags
end
class Message
has_many :users, :through => :tags
has_many :mailboxes, :through => :tags
has_many :tags
end
class Mailbox
has_many :tags
has_many :messages, :through => :tags
has_many :users, :through => tags
end
class Tag
belongs_to :user
belongs_to :message
belongs_to :mailbox
# this class has "read?", "starred", etc.
end
This enables a message to appear in multiple mailboxes, for multiple users, and each user can have his/her own "read?", "starred", etc. You can limit the logic if you want to ensure that a user has only one copy of a message, i.e. the message is not in two or more mailboxes for the same user.
To improve your schema, read the Rails Guides, especially about associations like these:
belongs_to
has_one
has_many
has_many :through
inverse_of
Also look at the Rails gem acts-as-taggable-on
http://rubygems.org/gems/acts-as-taggable-on
One way to think of a message schema is "a message belongs to a mailbox, and a mailbox has many messages" (this is how Yahoo does it). Another way to think of a message is "a message has many tags, and a mailbox is simply a search by tag" (this is how Gmail does it).
By the way, the Ruby mail gem is excellent. You can use it for creating messages, and look at how it converts headers like from, to, cc, etc.
You asked good questions:
1 - Should my new form be in inboxmessages or messages?
My opinion is that you will get the most benefit if you have a model for the message that is like an email, have a model for a mailbox (or tag). To create a new message, the new form would typically be in ./messages/new.html.erb
2 - Should I use accept_nested_for or should I use nested resources?
Nested resources are fine; see the Rails guide here:
http://guides.rubyonrails.org/routing.html#nested-resources
Nested attributes are also fine; see the API here:
A good rule of thumb is to only nest one level down, because after that it gets more complicated than its worth.
3 - Is my model/database is okay or not the best?
Not the best. A real-world message will typically have a sender and receiver(s). But you're modeling the sender and receiver in the inboxmessages table. Better to model the message with has_many receivers, and use a separate model for the user's interaction with the message for example a table called "marks" with fields "starred", "isread", etc. A mark belongs to a message and belongs to a user. A message has_many marks, and a user has_many marks.
4 - Are my foreign_key relationship well define?
In general, yes. Just be aware that email is surprisingly hard to model. A good rule of thumb is to index your foreign keys. Also look at Rails associations "inverse_of" and use it; this will help with speed and memory use.
I would have my classes set up something like this.
class Inbox
has_many :messages
belongs_to :user
end
class User
has_many :messages
has_one :inbox
end
class Message
belongs_to :user
belongs_to :inbox
has_many recipients, class_name: "User", foreign_key: "recipient_id"
end

has_many children and has_many parents

I'm trying to figure out a complex relation between a Model.
I have a model called "Concept", which has two inheriting types called "Skill" and "Occupation". Basicly this means that each concept represents a category, but a concept can also be a skill or an occupation when going deep enough into the hierychal tree.
I'm solving this hierachy by using STI. So my schema for the Concepts table looks like this:
class CreateConcepts < ActiveRecord::Migration
def self.up
create_table :concepts do |t|
t.string :uri, :null => false, :length => 255
t.string :type, :null => true, :length => 255
t.integer :isco_code, :null => true
t.timestamps
end
end
def self.down
drop_table :concepts
end
end
The type column determins whether the Concept is a real "Concept" or a "Skill"/"Occupation".
The problem now however the following relations:
EDIT:
A Concept can belong to a single parent Concept
An Occupation can belong to a single parent Concept
A Skill can belong to multiple parent Concepts
A skill has no children
An occupation has no children
so basicly you'd have something like this:
> concept1
> concept2 concept3
> concept4 concept5 concept6 concept7 skill1
> occup1 skill2 occup2 skill5
> occup7 skill2 occup3 skill4
> occup4 skill1 occup8
I hope the picture is a bit clear what I'm trying to explain.
Currently I have created the following migration to try to solve the parent-child relation but I'm not sure how to map this with the associations...
class CreateConceptLinks < ActiveRecord::Migration
def self.up
create_table :concept_links do |t|
t.integer :parent_id, :null => false
t.integer :child_id, :null => false
t.timestamps
end
end
def self.down
drop_table :concept_links
end
end
What I want to end up with is the following posssibilities:
concepta.parents => a Concept object
conceptb.children => an array of Conept objects
Occupation.parents => a Concept object
Occupation.children => []
Skill.parents => an array of Concept objects
Skill.children => []
Hope this is even possible...
You can model hierarchical relations in rails. You've got most of the way there with your migrations. Adding the relations below should allow you to do the method calls you'd like:
def Concept < ActiveRecord::Base
has_many :child_links, :class_name => 'ConceptLink', :foreign_key => 'parent_id'
has_many :children, :through => :child_links
has_many :parent_links, :class_name => 'ConceptLink', :foreign_key => 'child_id'
has_many :parents, :through => :parent_links
end
def ConceptLink < ActiveRecord::Base
belongs_to :child, :class_name => "Concept"
belongs_to :parent, :class_name => "Concept"
end
I'd also take a look at this blog posting which does a very good of explaining parent-child mappings in rails.

how do I get foreign_key to work in this simple has_many, belongs_to relationship?

I'm pulling data from Harvest. Here are my two models and schema:
# schema
create_table "clients", :force => true do |t|
t.string "name"
t.integer "harvest_id"
end
create_table "projects", :force => true do |t|
t.string "name"
t.integer "client_id"
t.integer "harvest_id"
end
# Client.rb
has_many :projects, :foreign_key => 'client_id' # not needed, I know
# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'
I'm trying to get the Projects to find their client by matching Project.client_id to a Client.harvest_id. Here is what I'm getting instead.
> Project.first.client_id
=> 187259
Project.first.client
=> nil
Client.find(187259).projects
=> []
Is this possible? Thanks!
Might not seem intuitive, but the foreign_key for both relations has to be the same. Let's say you decide to use harvest_id as the foreign key. It should be set up like this:
# Client.rb
has_many :projects, :foreign_key => 'harvest_id'
# Project.rb
belongs_to :client, :foreign_key => 'harvest_id'
You would also only have the harvest_id field in the projects table, since the client has_many projects.
Since your belongs_to relationship in Project model is on harvest_id, you have to ensure the harvest_id attribute is set in the project object.
> Project.first.harvest_id
=> ??
Your problem can occur if the harvest_id is not set.
Projects to find their client by matching Project.client_id to a Client.harvest_id
This does not seem to make sense as client and harvest are supposed to be different objects/records and you cannot match them.
It is like "Find apples where there are Orange-like seeds".
So we probably need more context.
You defined your relations the following way:
On the Project side you say "it is related to client via client_id", but on the Client you say that "it is related to Project via harvest_id"
There you have discrepancy.
So it seems you just have incorrect mappings defined.
Not sure how harvest_id is supposed to be used, so will make the assumption it is just association:
# Client.rb
has_many :projects
belongs_to :harvest
# Project.rb
belongs_to :client
belongs_to :harvest
# Harvest
has_one :client
has_one :project

Resources