user3437721
user3437721

Reputation: 2299

Model initialization and relationships

If I had a model with two levels of relationships, and accepts_nested_attributes_for:

Company which has_many addresses
Address which has many address_types

So if I initialize a Company, I assume it will create an Address and an AddressType also?

    @company = Company.new 
    @company.address.size #this should be 1?
    @company.address.address_type.size #this should be 1?

Question: How can I initialize the address, and the address_type with a default attribute, that is, the current_user_id

so for company in the controller, I can write:

@company.current_user_id = current_user.id

but current_user is not accessible in the model. Is there a way of initializing with the current_user for everything, not just the company? Whats the best approach to this?

can we do something like:

@company.address.new(current_user)

OR

In a before_save callback on the Address and AddressType models, could I have something like:

before_save: set_user

def set_user
  self.current_user_id = self.company.current_user.id
end

Upvotes: 0

Views: 302

Answers (1)

svelandiag
svelandiag

Reputation: 4320

No, when you initialize the model it will start with an empty array, so:

@company = Company.new 
@company.address.size #this is 0
@company.address.address_type.size #this is 0

You can't initialize those values by default, you need to send them when creating the company.

The Controller should tell the model instance

Working with the database is the model's job. Handling web requests, including knowing the user for the current request, is the controller's job.

Therefore, if a model instance needs to know the current user, a controller should tell it.

def create
  @item = Item.new
  @item.current_user = current_user # or whatever your controller method is
  ...
end

This assumes that Item has an attr_accessor for current_user.

update

You can loop the resources, in your controller add a private method:

def assign_current_user_to_address_type(company)
  company.addresses.each do |address|
    address.address_types.each do |address_type|
      address_type.create_user_id = current_user.id
    end
  end
 
end

Upvotes: 1

Related Questions