Is there a “first_or_build” method on has_many associations?

I’m not sure if there is anything built into rails that will do exactly what you want, but you could mimic the first_or_initialize code with a more concise extension than you are currently using, which I believe does what you want, and wrap it into a reusable extension such as the following. This is written … Read more

Hibernate unidirectional one to many association – why is a join table better?

Consider the situation where the owned entity type can also be owned by another parent entity type. Do you put foreign key references in the owned table to both parent tables? What if you have three parent types? It just doesn’t scale to large designs. A join-table decouples the join, so that the owned table … Read more

How do I pass an argument to a has_many association scope in Rails 4?

The way is to define additional extending selector to has_many scope: class Customer < ActiveRecord::Base has_many :orders do def by_account(account) # use `self` here to access to current `Customer` record where(:account_id => account.id) end end end customers.orders.by_account(account) The approach is described in Association Extension head in Rails Association page. To access the Customer record in … Read more

Could not find the association problem in Rails

In the ApplicationForm class, you need to specify ApplicationForms’s relationship to ‘form_questions’. It doesn’t know about it yet. Anywhere you use the :through, you need to tell it where to find that record first. Same problem with your other classes. So # application_form.rb class ApplicationForm < ActiveRecord::Base has_many :form_questions has_many :questions, :through => :form_questions end … Read more

Hibernate @OneToMany remove child from list when updating parent

Instead of replacing the collection (team.setUserTeamRoles(new HashSet<UserTeamRole>());) you have to clear() the existing one. This happens because if Hibernate loads the entity (and its collections) from DB, it “manages” them, ie. tracks their changes. Generally when using Hibernate it’s better not to create any setters for collections (lists, sets). Create only the getter, and clear … 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