user502052
user502052

Reputation: 15259

How to call correctly methods from a model relating to other controllers?

In my Ruby on Rails application I want to create a new profile and a new statistic for profile, all calling first the related method from the user model, and then from the profile model.

So...

... in my user model (user.rb) I have this:

...

has_one :profile

...
before_save :inizialize_user
...

private

def inizialize_user
  @user_profile = Profile.new
  self.user_profile_id = @user_profile.id
end

... in my profile model (profiles.rb) I have this:

...
belongs_to :user
...

before_save :inizialize_profile

private

def inizialize_profile
  @profile_statistic = ProfileStatistic.new
end

In the second block of code, on the "before_save" it instantiates a new profile statistic: "inspecting" @profile_statistic results a new object (correct!)

In the first block of code, on the "before_save" it doesn't instantiate a new profile: "inspecting" the @user_profile results nil (it must be a new profile object!)

The last part is my problem. Why it happens?

Upvotes: 1

Views: 335

Answers (1)

David Sulc
David Sulc

Reputation: 25994

When you call Profile.new, it only creates an instance in memory, it isn't saved to the database and therefore doesn't have an id attribute (i.e. @user_profile.id is nil).

I suggest you replace

@user_profile = Profile.new

with

@user_profile = Profile.create

create will save the instance and then @user_profile.id will not be nil.

You probably also wan to use before_create callbacks (not before_save), or you'll have new user profiles every time you save the model (e.g. after udpating). Also, you probably want to have

ProfileStatistic.create

instead of

ProfileStatistic.new

Upvotes: 3

Related Questions