The case:
tables:
teacher :id :name
course :id :name
teachercourse :id :teacher_id :course_id
How to do inner join to this 3 tables with rails?
Edit (my models):
class Course < ActiveRecord::Base
attr_accessible :name
has_many :teachercourses
has_many :teachers, through: :teachercourse
end
class Teacher < ActiveRecord::Base
attr_accessible :name
has_many :teachercourses
has_many :courses, through: :teachercourse
end
class Teachercourse < ActiveRecord::Base
attr_accessible :course_id, :teacher_id
belongs_to :course
belongs_to :teacher
end
Edit2 - where I need the join result(show action):
class CourseController < ApplicationController
def show
#not real syntax
#course=Course.find(join:teacher,teachercourse,teacher :: where course='javacourse');
end
end
Both your Teacher and Course models should also contain has_many :teachercourses
Then, if you're writing your code in the Teacher model it should be something like this:
joins(teachercourses: :course)
Edit:
If I understand the intention behind the code you posted, you're looking for all the teachers that teach in the java course. So this should work:
Teacher.joins(teachercourses: :course).where(course: {name: "javacourse"})
Related
My data model is fellows, the note and hashtag's relationship is many to many
class Note < ActiveRecord::Base
attr_accessible :title
attr_accessible :content
attr_accessible :created_at
default_scope -> { order(created_at: :desc) }
has_and_belongs_to_many :hashtags
end
class Hashtag < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :notes
end
class NoteHashtag < ActiveRecord::Base
t.belongs_to :note, index: true
t.belongs_to :hashtag, index: true
end
I want to inquire the sql like:
select Note.* from Note inner join NoteHashtag on Note.id=NoteHashtag.note inner join Hashtag on NoteHastag.hashtag=Hashtag.id where Hashtag.name="test"
How to convert the sql into the datamodel operation in ruby on rails4?
I try to use the:
#note=Note.joins(:hashtag).where(name: "test")
and the error is:
ActionView::Template::Error (Association named 'hashtag' was not found on Note;perhaps you misspelled it?):
You need has_many :through associations if you are going to explicitly define the join model NoteHashtag. If you delete that model, you can do #notes=Note.joins(:hashtag).where(name: "test") and ActiveRecord will generate the query you are expecting.
Otherwise you could do
class Note < ActiveRecord::Base
...
has_many :note_hashtags
has_many :hashtags, through: :note_hash_tags
end
class Hashtag < ActiveRecord::Base
attr_accessible :name
end
class NoteHashtag < ActiveRecord::Base
belongs_to :note
end
Then #notes = Note.joins(:note_hashtags).joins(:hash_tags).where(name: "test) would work.
Note that both of these will return more than one note.
You can get records from many to many relationship by doing this:-
#note = Note.joins(:hashtags).where('hashtags.name' => 'test')
Why don't you address this relationship originating from the proper model? Define your models like this:
class Note < ActiveRecord::Base
...
has_many :note_hashtags
has_many :hashtags, through: :note_hashtags
end
class Hashtag < ActiveRecord::Base
attr_accessible :name
has_many :note_hashtags
has_many :notes through: :notes_hashtags
end
class NoteHashtag < ActiveRecord::Base
belongs_to :note
belongs_to :hashtag
end
And then query like this:
Hashtag.where(name: 'Test').notes
In my Rails app I have Users and Forms.
class User < ActiveRecord::Base
has_many :admin_roles
#desired association below
#has_many :forms, through: :admin_roles
end
class Form < ActiveRecord::Base
has_one :department
end
The Users need to administrate the Forms through any level of an Organization.
class AdminRole < ActiveRecord::Base
belongs_to :organization
belongs_to :user
end
If assigned to a non-department organization the forms they have control over should come through the child departments.
The Forms are assigned to a departmental level only.
My model for the Organization is an STI model of 3 levels: market>subdomain>department
class Organization < ActiveRecord::Base
self.inheritance_column = :org_level
has_many :admin_roles
end
class Department < Organization
belongs_to :sub_domain, primary_key: :id, foreign_key: :parent_id
has_many :forms
end
class SubDomain < Organization
belongs_to :market, primary_key: :id, foreign_key: :parent_id
has_many :departments
end
class Market < Organization
has_many :sub_domains
end
The desired capability is to do user.forms and get all the associated forms back.
For example: Given there was a hierarchy of FooMarket>BarDomain>LoremDepartment
and a Form associated to LoremDepartment.
If a User is then tied to any of those 3 Organizations through the AdminRole it would allow for the return of the LoremDepartment Form.
Do you have to necessarily do it with associations ? u can always define an instance method in user model and back track it to forms.
But before that, just a reminder, you have to mention the foreign key in both the models for the association to work both ways.
class User < ActiveRecord::Base
attr_accessible :name
has_many :admin_roles
has_many :organizations, :through => :admin_roles
def forms
organizations.map(&:forms).flatten.uniq
end
end
class Department < Organization
belongs_to :sub_domain, primary_key: :id, foreign_key: :parent_id
has_many :forms, :foreign_key => :organization_id
end
class SubDomain < Organization
belongs_to :market, primary_key: :id, foreign_key: :parent_id
has_many :departments, foreign_key: :parent_id
def forms
departments.map(&:forms).flatten
end
end
class Market < Organization
has_many :sub_domains, foreign_key: :parent_id
def forms
sub_domains.map(&:forms).flatten
end
end
I tested this and it does work. But kinda round about.
I have a table rb which has many interfaces, then each interface has many interface_graph_data. Now my rb interface has_many relation seems to work fine, my only problem is the interface interface_graph_data relation. Here are my models.
class Rb < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :ip
validates_uniqueness_of :ip
validates_presence_of :username
validates_presence_of :password
has_many :interfaces
has_many :interfacegraphdata, :through => :interfaces
end
class Interface < ActiveRecord::Base
has_many :interfacegraphdata
end
class InterfaceGraphData < ActiveRecord::Base
end
The name of relation should be interface_graph_dates
upd:
You also missed
class InterfaceGraphData < ActiveRecord::Base
belongs_to :rb
belongs_to :interface
end
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
Im setting up a reminder service that sends deals via email in relation to a persons interests AND city.. Basically, the user inputs important dates (friends bday, anniversary ect) and the interests of that special person.
I want to send them deals based on 1)the users city and 2)the interests of the related person
How should i setup my associations for the Deal model?
What i have so far..
class User < ActiveRecord::Base
belongs_to :city
has_many :person_interests, :as => :person
has_many :interests, :through => :person_interests
end
class City < ActiveRecord::Base
attr_accessible :name
belongs_to :province
has_many :users
end
class PersonInterest < ActiveRecord::Base
belongs_to :interest
belongs_to :person, :polymorphic => true
end
class Interest < ActiveRecord::Base
has_many :person_interests
end
Thanks!
If a deal could apply to more than one interest, you'd start with something like:
class Deal < ActiveRecord::Base
belongs_to :interests
belongs_to :city
end
class City < ActiveRecord::Base
attr_accessible :name
belongs_to :province
has_many :users
has_many :deals
end
class Interest < ActiveRecord::Base
has_many :person_interests
has_many :deals
end
And then you could do something like
#relevant_deals = #city.deals.where(:interest_id => 'abc')
or
#relevant_deals = #interest.deals.where(:city_id => 'def')
My models look something like this:
class User < ActiveRecord::Base
attr_accessible: :name
has_many :reviews
end
class Product < ActiveRecord::Base
attr_accessible: :name
has_many :reviews
end
class Review < ActiveRecord::Base
attr_accessible: :comment
belongs_to :user
belongs_to :product
validates :user_id, :presence => true
validates :product_id, :presence => true
end
I am trying to figure out what the best way is to create a new Review, given that :user_id and :product_id are not attr_accessible. Normally, I would just create the review through the association ( #user.reviews.create ) to set the :user_id automatically, but in this case I am unsure how to also set the product_id.
My understanding is that if I do #user.reviews.create(params), all non attr_accessible params will be ignored.
You can do:
#user.reviews.create(params[:new_review])
...or similar. You can also use nested attributes:
class User < ActiveRecord::Base
has_many :reviews
accepts_nested_attributes_for :reviews
...
See "Nested Attributes Examples" on http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html.
It seems you would like to implement a many-to-many relationship between a User and Product model, with a Review model serving as a join table to connect the two with an added comment string. This can be accomplished with a has many through association in Rails. Start by reading the Rails Guides on Associations.
When setting up your Review model, add foreign keys for the User and Product:
rails generate model review user_id:integer product_id:integer
And set up your associations as follows:
class User < ActiveRecord::Base
has_many :reviews
has_many :products, through: :reviews
end
class Product < ActiveRecord::Base
has_many :reviews
has_many :users, through: :reviews
end
class Review < ActiveRecord::Base
# has comment string attribute
belongs_to :user
belongs_to :product
end
This will allow you to make calls such as:
user.products << Product.first
user.reviews.first.comment = 'My first comment!'
Here's how you would create a review:
#user = current_user
product = Product.find(params[:id])
#user.reviews.create(product: product)