I have an array of posts called #posts. Post model has_many :feelings :through => :feelingships.
How do I take the array of posts and narrow them it down to only the posts with a specific feeling?
I tried the code below but it doesn't work :(
#specific_feeling_posts = #posts.feeling.where(:feeling => "happy")
Models
class Post < ActiveRecord::Base
has_many :feelingships
has_many :feelings, :through => :feelingships
belongs_to :user
end
class Feeling < ActiveRecord::Base
has_many :feelingships
has_many :posts, :through => :feelingships
end
class Feelingship < ActiveRecord::Base
belongs_to :post
belongs_to :feeling
end
#happy_posts = Post.joins(:feelings).where("feelings.title = ?", "happy")
That should work.
#specific_feelings_post=Post.join(:feelings).where("feelings.title= ?","specific_feeling")
Its the same line as bricker has written above. The question mark is to avoid SQL injection.
In short, the security of the database is handled by the ActiveRecord in Rails. By doing this, you will create properly escaped SQl and is immune from SQL injection.
Related
I have these 2 models, and I'm trying to add an association between them so I can add some extra details later:
class Ticket < ActiveRecord::Base
belongs_to :user
has_many :event_tickets
has_many :events, :through => :event_tickets
end
class Event < ActiveRecord::Base
has_many :event_tickets
has_many :tickets, :through => :event_tickets
end
class EventTicket < ActiveRecord::Base
belongs_to :event
belongs_to :ticket
end
I've tried adding an association like this, just to see it's working:
event_ticket = EventTicket.new(:ticket => ticket, :event => Event.all[0])
event_ticket.save!
This gives me:
can't write unknown attribute `ticket_id`
The ticket and event exist and are working fine, but can't get the event_ticket object working.
What am I doing wrong?
It sounds like you don't have an event_tickets table, or at least it doesn't have a ticket_id column. Are you sure you wrote the migration and ran it?
I've got a Person who can be linked to many Structures (structure is polymorphic)
I've got a Venue, who can have many People, as a structure.
I've got a Journal, who can have many People, as a structure.
Here is my modelization :
class Venue < ActiveRecord::Base
has_many :structure_people, :as => :structure
has_many :people, :through => :structure_people
end
class Journal < ActiveRecord::Base
has_many :structure_people, :as => :structure
has_many :people, :through => :structure_people
end
class Person < ActiveRecord::Base
has_many :structure_people
has_many :structures, :through => :structure_people
end
class StructurePerson < ActiveRecord::Base
belongs_to :structure, polymorphic: true
belongs_to :person
end
My problem :
when i try to get people on a Venue or on a Journal, it works. Cool :)
BUT
when i try to get structures on a person, i've got an error :
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'Person#structures' on the polymorphic object 'Structure#structure'.
Anyone could help me to solve this ?
Thanks a lot.
Christophe
I think it's a restriction of Rails, because has_many association will guess a class_name automatically. But polymorphic association may returns multiple class_name. Do you mind use this:
class Person < ActiveRecord::Base
has_many :structure_people
has_many :venues, :through => :structure_people
#Journal is the same.
end
class StructurePerson < ActiveRecord::Base
belongs_to :structure, polymorphic: true
belongs_to :venue, :foreign_key => 'structure_id', :conditions => {:structure_type => 'Venue'}
belongs_to :person
end
Although it is an ugly solution...
I think you can choose an alternative way.
class Person < ActiveRecord::Base
has_many :structure_people
def structures
structure_people.map(&:structure)
end
end
You can't get chaining function of has_many, but you can get polymorphic structures :)
I have the following tables:
class FinalExam < ActiveRecord::Base
belongs_to :course
has_many :pages, :as => :course_unit, :dependent => :destroy
end
class Page < ActiveRecord::Base
belongs_to :course_unit, :polymorphic => true
has_one :quiz
has_one :slide
end
class Quiz < ActiveRecord::Base
belongs_to :page
end
class Answers < ActiveRecord::Base
belongs_to :quiz
end
So, we have Answer.Quiz.Page.FinalExam
Given the FianlExam id, what is the fastest way to find all Answers count ? how to get it ?
I can re-design the DB to have belongs_to :final_exam in Answers
class Answers < ActiveRecord::Base
belongs_to :quiz
belongs_to :final_exam
end
this way, I can say Answers.where(:final_exam_id=> params[:id]).count
Do I have to change the DB design ? or its a matter of a query ?
I need an expert advice please.
First of all I'm guessing that Quiz should read:
class Quiz < ActiveRecord::Base
belongs_to :page
has_many :answers
end
If so you can add these lines to your FinalExam model:
has_many :quizzes, :through => :pages
has_many :answers, :through => :quizzes
Allowing you to then call
FinalExam.first.answer.count
(Note: if you're on a version of Rails < 3.1, you'll need this plugin)
The drawback to this approach is that it becomes slow with a lot of data. In this case, you'd want to set up a counter cache in the FinalExam that updates every time an answer is added. It'd a little more complicated because of the many-layered relationships you have; see this post for more info:
counter_cache has_many_through sql optimisation, reduce number of sql queries
I have three models
class Collection < ActiveRecord::Base
has_many :presentations
has_many :galleries, :through => :presentations
end
class Gallery < ActiveRecord::Base
has_many :presentations
has_many :collections, :through => :presentations
end
class Presentation < ActiveRecord::Base
belongs_to :collection
belongs_to :gallery
end
How do I get all the collections that do not belong to a given gallery?
My SQL knowledge is only rudimentary. I also want to let Rails (2.3) do the work without using explicitly a SQL expression.
Out of the box, you technically have to write some SQL (where clause)...
gallery_to_exclude = Gallery.first
Collection.find(:all,
:include => :presentations,
:conditions => ['presentations.gallery_id IS NULL OR presentations.gallery_id != ?',
gallery_to_exclude.id])
If you want to use Searchlogic, you can avoid this, though:
Collection.presentations_gallery_id_is_not(gallery_to_exclude.id).all
I have a many to many relationship in rails. All database tables are named accordingly and appropriately. All model files are plural and use underscore to seperate words. All naming comventions are followed by ruby and rails standards. I'm using has many through in my models like this:
has_many :users, :through => :users_posts #Post model
has_many :posts, :through => :users_posts #User model
belongs_to :users #UsersSource model
belongs_to :posts #UsersSource model
What else could this error be from?
ActiveRecord::HasManyThroughAssociationNotFoundError in UsersController#welcome
Could not find the association :users_posts in model Post
You need to define the join model as a separate association when using has_many :through:
class Post < ActiveRecord::Base
has_many :user_posts
has_many :users, :through => :user_posts
end
class User < ActiveRecord::Base
has_many :user_posts
has_many :posts, :through => :user_posts
end
class UserPost < ActiveRecord::Base
belongs_to :user # foreign_key is user_id
belongs_to :post # foreign_key is post_id
end
This works best when you need to keep data that pertains to the join model itself, or if you want to perform validations on the join separate from the other two models.
If you just want a simple join table, it's easier to use the old HABTM syntax:
class User < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :users
end