HABTM Relationship — How Can I Find A Record Based On An Attribute Of The Associated Model

You need to include the interests table. @events = Event.all(:include => :interests, :conditions => [“interests.id = ?”, 4]) You had it right in your post, but you didn’t pluralize interests. Update Because this answer is still getting attention, I thought it might be a good idea to update it using ActiveRecord::Relation syntax since the above … Read more

How do I remove a single HABTM associated item without deleting the item itself?

I tend to use has_many :through, but have you tried student.classes.delete(science) I think needing to have the target object, not just the ID, is a limitation of HABTM (since the join table is abstracted away for your convenience). If you use has_many :through you can operate directly on the join table (since you get a … Read more

Rails HABTM – Properly removing an association

According to the Rails documentation: collection.delete(object, …) Removes one or more objects from the collection by removing their associations from the join table. This does not destroy the objects. Brilliant reference here for you You can use: product = Product.find(x) special = product.specials.find(y) product.specials.delete(special) This creates ActiveRecord objects for both the object you’re trying to … Read more

How to create has_and_belongs_to_many associations in Factory girl

Here is the solution that works for me. FactoryGirl.define do factory :company do #company attributes end factory :user do companies {[FactoryGirl.create(:company)]} #user attributes end end if you will need specific company you can use factory this way company = FactoryGirl.create(:company, #{company attributes}) user = FactoryGirl.create(:user, :companies => [company]) Hope this will be helpful for somebody.

Rails migration for has_and_belongs_to_many join table

Where: class Teacher < ActiveRecord::Base has_and_belongs_to_many :students end and class Student < ActiveRecord::Base has_and_belongs_to_many :teachers end for rails 4: rails generate migration CreateJoinTableStudentTeacher student teacher for rails 3: rails generate migration students_teachers student_id:integer teacher_id:integer for rails < 3 script/generate migration students_teachers student_id:integer teacher_id:integer (note the table name lists both join tables in alphabetical order) and … Read more

Rails has_and_belongs_to_many migration

You need to add a separate join table with only a restaurant_id and user_id (no primary key), in alphabetical order. First run your migrations, then edit the generated migration file. Rails 3 rails g migration create_restaurants_users_table Rails 4: rails g migration create_restaurants_users Rails 5 rails g migration CreateJoinTableRestaurantUser restaurants users From the docs: There is … Read more