Questions tagged [associations]

Associations typically refer to relationships between models in ORMs such as ActiveRecord.

Filter by
Sorted by
Tagged with
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.
user avatar
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 => :...
Sergey's user avatar
  • 4,732
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], :...
user26270's user avatar
  • 7,054
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 ...
hguser's user avatar
  • 35.6k
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 ...
Josh Close's user avatar
  • 23.1k
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: ...
themirror's user avatar
  • 10.1k
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 ...
espinet's user avatar
  • 1,703
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....
ClosureCowboy's user avatar
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 ...
opsb's user avatar
  • 29.8k
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 < ...
JonathanSimmons's user avatar
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 <&...
BvuRVKyUVlViVIc7's user avatar
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 ...
Mark's user avatar
  • 5,343
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 ...
user2158382's user avatar
  • 4,500
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 ...
Pedro Gabriel Lima's user avatar
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 ...
Andrew's user avatar
  • 2,158
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 ...
William Jones's user avatar
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 ...
brad's user avatar
  • 32.1k
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/...
Victor Lam's user avatar
  • 3,670
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 ...
Loenvpy's user avatar
  • 899
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 ...
Andna's user avatar
  • 6,639
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 ...
duduklein's user avatar
  • 10.3k
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 ...
Lars Dol's user avatar
  • 765
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 ...
Rob's user avatar
  • 780
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 ...
Hommer Smith's user avatar
  • 27.4k
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 ...
hrdwdmrbl's user avatar
  • 5,071
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 ...
Finks's user avatar
  • 1,671
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 => :...
thenengah's user avatar
  • 42.8k
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 ...
Ryan's user avatar
  • 6,562
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 ...
KingPong's user avatar
  • 1,449
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 ...
ryanprayogo's user avatar
  • 11.7k
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 ...
humble_coder's user avatar
  • 2,797
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....
Ash's user avatar
  • 25.1k
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....
AndaP's user avatar
  • 1,308
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 ...
Rob Sobers's user avatar
  • 20.9k
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 ...
Matt Briggs's user avatar
  • 41.7k
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 ...
m_x's user avatar
  • 12.5k
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 < ...
Julio G Medina's user avatar
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 ...
UrLicht's user avatar
  • 949
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 ...
Filippo's user avatar
  • 1,151
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 ...
user4584963's user avatar
  • 2,473
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 ...
Talha5389's user avatar
  • 738
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 <...
ardavis's user avatar
  • 9,865
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::...
crackpot's user avatar
  • 301
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 ...
dmt2989's user avatar
  • 1,610
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 ...
user12882's user avatar
  • 4,742
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/...
lintmouse's user avatar
  • 5,099
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 ...
Igor Martins's user avatar
  • 2,025
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 ...
Billy Gray's user avatar
  • 1,747
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"...
bobomoreno's user avatar
  • 2,848

1
2 3 4 5
123