drew_94301
drew_94301

Reputation: 3

How to use create_association in ruby-on-rails

I am having trouble getting the create_association(attributes = {}) method to work for associated models in Rails.

class Gwgiftwhip < ActiveRecord::Base
  has_one :gift, :autosave => true, :dependent => :destroy
  validates :gift, :presence => true  
end

class Gift < ActiveRecord::Base
  belongs_to :gwgiftwhip
end

The belongs_to section in the Active Record Associations Guide suggests that you should be able to use the method: create_association(attributes = {}) to create a related model and save it when using the belongs_to association. However, the below implementation results in a save error due to the related model parameter, 'gift' not being set.

class GiftsController < ApplicationController
...
def inbound
  @gift = Gift.new(params.slice(*Gift.new.acceptable))    
  if @gift.create_gwgiftwhip({:user_id => @gift.user_id}, :without_protection => true)
    ...
  end
end

The below works, but seems like it's outside the intended use. It is creating a related model, then setting itself as the related model. This requires another step to then save.

class GiftsController < ApplicationController
...
def inbound
  @gift = Gift.new(params.slice(*Gift.new.acceptable))    
  @gift.create_gwgiftwhip({:user_id => @gift.user_id}, :without_protection => true).gift = @gift
  if @gift.gwgiftwhip.save
    ...
  end
end

Upvotes: 0

Views: 1065

Answers (1)

jshkol
jshkol

Reputation: 1877

Try turning it around:

def inbound
  @gift = Gift.new( params.slice( *Gift.new.acceptable ) )    
  if Gwgiftwhip.create( {user_id: @gift.user_id, 
                            gift: @gift}, without_protection: true )
    ...
  end
end

You might also conisder overriding gift= on Gwgiftwhip so that setting gift sets user_id automatically. Example:

class Gwgiftwhip
  has_one :gift, :autosave => true, :dependent => :destroy

  def gift=( gift )
    super( gift )
    self.user_id = gift.user_id
  end
end

Upvotes: 1

Related Questions