Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

Allow Active Record Model to Assign Association using String

I have a fairly basic set of models where a 'Project' has one 'Owner'. I'd like to allow users to enter the owner's name when creating a new project. If owner doesn't exist, a new one should be created. Does a good way to do this exist? I've been thinking about using attr_accessor and before_validation however it seems it would conflict with the relationship. Any ideas? Thanks!

Upvotes: 0

Views: 283

Answers (2)

Jeremy
Jeremy

Reputation: 4930

I'd use something along the lines of this in your controller:

def update
  Project.transaction do
    @project.owner = Owner.find_or_create_by_name(params[:project].delete(:owner_name))
    @project.attributes = params[:project]
    @project.save!
  end
end

Upvotes: 1

Fábio Batista
Fábio Batista

Reputation: 25270

Use something different than the name of your relationship... owner_name should be fine. Then write the necessary before_validation method.

Upvotes: 1

Related Questions