Questions tagged [associations]
Associations typically refer to relationships between models in ORMs such as ActiveRecord.
6,134
questions
578
votes
21
answers
490k
views
What is the difference between association, aggregation and composition?
What is the difference between association, aggregation, and composition?
Please explain in terms of implementation.
213
votes
4
answers
113k
views
Rails :dependent => :destroy VS :dependent => :delete_all
In rails guides it's described like this:
Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :...
210
votes
6
answers
73k
views
What is causing this ActiveRecord::ReadOnlyRecord error?
This follows this prior question, which was answered. I actually discovered I could remove a join from that query, so now the working query is
start_cards = DeckCard.find :all, :joins => [:card], :...
203
votes
4
answers
165k
views
What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?
What is the difference between Unidirectional and Bidirectional associations?
Since the table generated in the db are all the same,so the only difference I found is that each side of the bidiretional ...
164
votes
5
answers
102k
views
MongoDB Many-to-Many Association
How would you do a many-to-many association with MongoDB?
For example; let's say you have a Users table and a Roles table. Users have many roles, and roles have many users. In SQL land you would ...
161
votes
5
answers
106k
views
Rails migration: t.references with alternative name?
So I have a create_table like this for Courses at a School:
create_table :courses do |t|
t.string :name
t.references :course
t.timestamps
end
but I want it to reference two other courses like:
...
154
votes
3
answers
87k
views
Rails: Using build with a has_one association in rails
In this example, I create a user with no profile, then later on create a profile for that user. I tried using build with a has_one association but that blew up. The only way I see this working is ...
127
votes
5
answers
83k
views
Build vs new in Rails 3
In the Rails 3 docs, the build method for associations is described as being the same as the new method, but with the automatic assignment of the foreign key. Straight from the docs:
Firm#clients....
125
votes
11
answers
48k
views
How to create has_and_belongs_to_many associations in Factory girl
Given the following
class User < ActiveRecord::Base
has_and_belongs_to_many :companies
end
class Company < ActiveRecord::Base
has_and_belongs_to_many :users
end
how do you define ...
95
votes
8
answers
63k
views
Rails association with multiple foreign keys
I want to be able to use two columns on one table to define a relationship. So using a task app as an example.
Attempt 1:
class User < ActiveRecord::Base
has_many :tasks
end
class Task < ...
84
votes
8
answers
43k
views
Rails - Best-Practice: How to create dependent has_one relations
What's the best practice to create has_one relations?
For example, if I have a user model, and it must have a profile...
How could I accomplish that?
One solution would be:
# user.rb
class User <&...
81
votes
9
answers
30k
views
What is the best way to implement Polymorphic Association in SQL Server?
I have tons of instances where I need to implement some sort of Polymorphic Association in my database. I always waste tons of time thinking through all the options all over again. Here are the 3 I ...
76
votes
4
answers
62k
views
Rails: ActiveRecord query based on association value
I have 2 models. Report and Server that have a belongs_to and has_many relationship. I created an accessor method using delegate that allows a Report to find its associated Server.company_id. Now, I ...
74
votes
3
answers
67k
views
Rails has_one :through association
Rails has a has_one :through association that helps set up a one-to-one association with a third model by going through a second model. What is the real use of that besides making a shortcut ...
65
votes
8
answers
48k
views
Validation failed Class must exist
I have been (hours) trouble with associations in Rails. I found a lot of similar problems, but I couldn't apply for my case:
City's class:
class City < ApplicationRecord
has_many :users
end
...
65
votes
4
answers
59k
views
add associations to exisiting models
I'm wondering how I can add associations to my models. Suppose, I generate two models
rails generate model User
rails generate model Car
Now I want to add an associations so that the models acquire ...
64
votes
4
answers
39k
views
Ruby-on-Rails: Multiple has_many :through possible?
Is it possible to have multiple has_many :through relationships that pass through each other in Rails? I received the suggestion to do so as a solution for another question I posted, but have been ...
57
votes
4
answers
20k
views
rails override default getter for a relationship (belongs_to)
So I know how to override the default getters for attributes of an ActiveRecord object using
def custom_getter
return self[:custom_getter] || some_default_value
end
I'm trying to achieve the same ...
56
votes
7
answers
46k
views
How to use ActiveAdmin on models using has_many through association?
I am using ActiveAdmin gem in my project.
I have 2 models using has_many through association. The database schema looks exactly the same as the example in RailsGuide. http://guides.rubyonrails.org/...
54
votes
3
answers
36k
views
Rails 4 find or create by method doesn't work
I have a one to many association between jobs and companies and it works fine. In the job form view I have text_field for the company name with an autocomplete feature. The autocomplete works fine but ...
53
votes
8
answers
50k
views
UML aggregation vs association
From Martin Fowler's UML Distilled:
In the pre-UML days, people were usually rather vague on what was aggregation and what was
association. Whether vague or not, they were always inconsistent with ...
52
votes
3
answers
59k
views
How to build many-to-many relations using SQLAlchemy: a good example
I have read the SQLAlchemy documentation and tutorial about building many-to-many relation but I could not figure out how to do it properly when the association table contains more than the 2 foreign ...
51
votes
9
answers
36k
views
Sails.js populate nested associations
I've got myself a question regarding associations in Sails.js version 0.10-rc5. I've been building an app in which multiple models are associated to one another, and I've arrived at a point where I ...
50
votes
4
answers
20k
views
How do I prevent deletion of parent if it has child records?
I have looked through the Ruby on Rails guides and I can't seem to figure out how to prevent someone from deleting a Parent record if it has Children. For example. If my database has CUSTOMERS and ...
50
votes
4
answers
43k
views
Correct way of testing "associations" with Rspec?
I am trying to test the following scenario:
-> I have a model called Team which it just makes sense when it has been created by a User. Therefore, each Team instance has to be related to a User.
In ...
50
votes
3
answers
45k
views
When will ActiveRecord save associations?
I know that it will save associations when autosave: true as per https://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html
I know that it will save associations that are constructed ...
46
votes
2
answers
62k
views
build method on ruby on rails
New to rails and I'm following the Depot project found in the Agile web development with rails 3.1. Everything was fine until I got lost when the book used the "build" method.
@cart = current_cart
...
45
votes
2
answers
15k
views
Rails Associations - has_many => :through - but same model
What I am trying to do:
I have a blog and want to show related posts below the main post.
class Post < ActiveRecord::Base
has_many :related_posts
has_many :posts, :through => :...
43
votes
2
answers
18k
views
Same Model for Two belongs_to Associations
I have an model PointOfContact which has_many Systems. From the Systems side I want to identify the PointOfContact as either the technical_manager or project_manager (or both). While still only ...
42
votes
8
answers
13k
views
Rails idiom to avoid duplicates in has_many :through
I have a standard many-to-many relationship between users and roles in my Rails app:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, :through => :user_roles
end
I ...
41
votes
3
answers
33k
views
Rails association - how to add the 'has_many' object to the 'owner'
In my app, a user has many score_cards and a score_card belongs to a user
The question is, whenever I create a new score_card, ie, ScoreCardsController.create gets called, how do I add this newly ...
41
votes
2
answers
22k
views
How do I remove a single HABTM associated item without deleting the item itself?
How do you remove a HABTM associated item without deleting the item itself?
For example, say I have 3 Students that are in a Science class together. How do I remove the Science objects from the ...
40
votes
2
answers
29k
views
Could not find the association problem in Rails
I am fairly new to Ruby on Rails, and I clearly have an active record association problem, but I can't solve it on my own.
Given the three model classes with their associations:
# application_form....
39
votes
1
answer
72k
views
Hibernate @OneToMany remove child from list when updating parent
I have the following entities:
TEAM
@Entity
@Table
public class Team {
[..]
private Set<UserTeamRole> userTeamRoles;
/**
* @return the userTeamRoles
*/
@OneToMany(cascade = { CascadeType....
36
votes
3
answers
26k
views
How do I pass an argument to a has_many association scope in Rails 4?
Rails 4 lets you scope a has_many relationship like so:
class Customer < ActiveRecord::Base
has_many :orders, -> { where processed: true }
end
So anytime you do customer.orders you only get ...
35
votes
4
answers
19k
views
Rails: belongs_to vs has_one
A bit of a newbie question on rails associations.
I have a Bug model, and a Status model. Status is basically just a key/value pair table. Out of the choices available, I would say Bug has_one Status ...
34
votes
1
answer
11k
views
Is there a "first_or_build" method on has_many associations?
In rails 3.2+, you can do this :
SomeModel.some_scope.first_or_initialize
Which means you can also do :
OtherModel.some_models.first_or_initialize
I find this pretty useful, but i'd like to have ...
33
votes
6
answers
25k
views
rails scope to check if association does NOT exist
I am looking toward writing a scope that returns all records that do not have a particular association.
foo.rb
class Foo < ActiveRecord::Base
has_many :bars
end
bar.rb
class Bar < ...
33
votes
2
answers
27k
views
Hibernate unidirectional one to many association - why is a join table better?
In this document (scroll down to the Unidirectional section):
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-association-collections
it says that a ...
32
votes
6
answers
44k
views
How to join unrelated entities with the JPA Criteria API
Two database tables have a foreign key relationship.
They are mapped to two entities A and B by JPA, but the join columns are manually removed from the entities, so in JPA world classes A and B are ...
31
votes
4
answers
31k
views
Rails - check if record exists in has_many association
I'm not sure if my question is worded correctly.
I have three models: User, Item, and UserItem.
user has_many :user_items
user has_many :items, through :user_items
item has_many :user_items
item ...
31
votes
1
answer
42k
views
C++ : Association, Aggregation and Composition
I'm beginning to study OOAD and I'm having difficulty finding a C++ code example that'd illustrate how Association, Aggregation and Composition are implemented programmatically. (There are several ...
30
votes
2
answers
35k
views
Rails Model, belongs to many
I'm having a hard time figuring out how to association one of my models with multiple of another.
As it is now, I have:
class ModelA < ActiveRecord::Base
has_many :model_b
end
class ModelB <...
30
votes
4
answers
44k
views
belongs_to with :class_name option fails
I have no idea what went wrong but I can't get belongs_to work with :class_name option. Could somebody enlighten me. Thanks a lot!
Here is a snip from my code.
class CreateUsers < ActiveRecord::...
30
votes
4
answers
62k
views
Rails console: Unable to autoload constant
I have a Customer_ratings model that allows users to leave feedback on each other. The web app is working properly, and feedback is collected, stored and displayed.
I wanted to go in and delete ...
30
votes
4
answers
9k
views
Trouble with accepts_nested_attributes_for on validating foreign key
I am using Ruby on Rails v3.2.2. I would like to solve the issue related to the validation of a foreign key when using accepts_nested_attributes_for and validates_associated RoR methods. That is, I ...
30
votes
1
answer
48k
views
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
"The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."
I am getting this error in Entity Framework 4.4 when updating/...
30
votes
5
answers
9k
views
How to do has_many and has_one association in same model?
I need to do two associations in the same model. Where:
Team has_many User
Now, I want that Team has_one Leader
This "Leader" will be a User
Im trying to use has_one throught but I think that ...
29
votes
4
answers
34k
views
Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship
I cannot seem to get a nested form to generate in a rails view for a belongs_to relationship using the new accepts_nested_attributes_for facility of Rails 2.3. I did check out many of the resources ...
29
votes
3
answers
21k
views
FactoryGirl override attribute of associated object
This is probably silly simple but I can't find an example anywhere.
I have two factories:
FactoryGirl.define do
factory :profile do
user
title "director"
bio "I am very good at things"...