Case:
I have a model (" ride_request ")
in ride_request there are two fields ( pickup_location , dropoff_location )
both fields (pickup and dropoff) are instances of one model (location)
Here is my migrate
create_table :ride_requests do |t|
t.integer :pickup_location
t.integer :dropoff_location
Question:
How do I create a relation to location in the fields pickup/drop when normaly you would use location_id?
you can use :class_name and :foreign_key to indicate the differences
Class RideRequest
belongs_to :pickup, :class_name => "location", :foreign_key => "pickup_location"
belongs_to :dropoff, :class_name => "location", :foreign_key => "dropoff_location"
Related
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)
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'
I am modelling users and movies with "liked" and "recommeded".
The models are as follows:
class Movie < ActiveRecord::Base
attr_accessible :title, :imbd_id
has_and_belongs_to_many :liked_by, :class_name => "User",
:conditions => { "type" => "like" }
has_and_belongs_to_many :recommended_by, :class_name => "User",
:conditions => { "type" => "recommend" }
end
class User < ActiveRecord::Base
has_and_belongs_to_many :movies_liked, :class_name => "Movie",
:conditions => { "type" => "like" }
has_and_belongs_to_many :movies_recommended, :class_name => "Movie",
:conditions => { "type" => "recommend" }
end
with one table to map the relationship:
create_table "movies_users", :id => false, :force => true do |t|
t.integer "user_id"
t.integer "movie_id"
t.string "type" # this can be "like" or "recommend"
t.string "status_id"
t.datetime "created_at"
t.datetime "updated_at"
end
Now I am getting an error when I try to do
u = User.first
m = Movie.first
u.movie_liked << m
with the following error
ruby-1.9.2-p290 :003 > u.movies_tweeted << m
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: movies.type: SELECT * FROM "movies" INNER JOIN "movies_users" ON "movies".id = "movies_users".movie_id WHERE ("movies_users".user_id = 1 AND ("movies"."type" = 'like'))
Any idea I can structure it nicely so I can just use the << operator and it will automatically assign the correct type?
Thanks!
You can create Recommendation and Like models and use them to join the Users with Movies. Or just a single model called don't know how(RecommendLike?), if you really wish to save on one table. And then:
User
has_many :recommendations
has_many :movies_recommended, :class_name => "Movie", :through => :recommendations
has_many :likes
has_many :movies_liked, :class_name => "Movie", :through => :likes
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.
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