fbelanger fbelanger - 2 years ago 61
Ruby Question

Ruby on Rails Association build and assign 2 related associations

So I've got a

model, a
model, and a

A user
has_many :maintenance_requests
, but
belongs_to :building

A maintenance requests
belongs_to :building
, and
belongs_to: user

I'm trying to figure out how to send a new, then create a maintenance request.

What I'd like to do is:

@maintenance_request = current_user.building.maintenance_requests.build(permitted_mr_params)
=> #<MaintenanceRequest id: nil, user_id: 1, building_id: 1>

And have a new maintenance request with the user and building set to it's parent associations.

What I have to do:

@maintenance_request = current_user.maintenance_requests.build(permitted_mr_params)
@maintenance_request.building = current_user.building

It would be nice if I could get the maintenance request to set its building based of the user's building.

Obviously, I can work around this, but I'd really appreciate the syntactic sugar.

Answer Source

My approach would be to skip

maintenance_request belongs_to :building

since it already belongs to it through the user. Instead, you can define a method

class MaintenanceRequest
    belongs_to :user

    def building

    #more class stuff

Also, in building class

class Building
     has_many :users
     has_many :maintenance_requests,  through: :users

    #more stuff

So you can completely omit explicit building association with maintenance_request

UPDATE Since users can move across buildings, you can set automatic behavior with a callback. The job will be done like you do it, but in a more Railsey way

class MaintenanceRequest
     before_create {

So, when you create the maintenance_request for the user, the building will be set accordingly

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download