0

Rails 4.1, Ruby 2.1.

I'm trying to build a new model through an association, and I need an ID reference to an object that has not been created yet.

I have something like this:

@user = User.new(user_params) @user.adminships.build(adminable_type: 'Program', adminable_id: current_user.programs.first.id) @user.save 

This is weird to me since I expected the association to be set up automatically, but for some reason I get a ["User can't be blank"] error.

When I run the code in the Rails console, it seems to work fine.

Any ideas?

3 Answers 3

1

It appears as though the problem was that on my Adminship model, I was doing:

validates :adminable_type, :adminable_id, :user_id, presence: true

I removed this, and added this instead: validates_presence_of :user

Appears to work now.

Sign up to request clarification or add additional context in comments.

Comments

0

You are right when you say that @user does not have an id yet, but when you do a save on the @user instance after building the adminships relation, it should set an id for both:

@user = User.new(user_params) @user.adminships.build(adminable_type: 'Program', adminable_id: current_user.programs.first.id) @user.save 

This should save validates the user, and if it is valid, save the database and then save the Adminship and with the new user id.

1 Comment

This is essentially the code I have above, which doesn't work. When I try to save, I get an error: ["User can't be blank"]. It doesn't make sense to me because I build through the association, and the association appears to be set up properly.
0

By using create instead of new which ActiveRecord will first try to save with validations. You can then call @user.id on the association with the existing code that you already have.

You could use @user = User.create(user_params)

create method Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

new method New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.