Domanda

My User model doesn't have a :name field but I want to include a :name field in my sign up form which will be used to create a record of another model in an after_create.

class User < ActiveRecord::Base
  after_create :create_thing

private
  def create_thing
    @thing = Thing.new
    @thing.name = <here's where I need help>
    @thing.save!
  end
end

How can I get the name from the sign up form?

È stato utile?

Soluzione

In your model add attr_accessor for name

attr_accessor :name

This will allow you to add it to a form and use it to generate the proper data in your after_create

Altri suggerimenti

Just as @trh said you can use a attr_accessor, but if you need to have it do some logic your gonna need to make getter and/or setter methods to accompany the attr_accessor.

class User < ActiveRecord::Base
  attr_accessor :name
  after_create :create_thing

  def name
    #if need be do something to get the name 
    "#{self.first_name} #{self.last_name}"
  end

  def name=(value)
    #if need be do something to set the name 
    names = value.split
    @first_name = names[0]
    @last_name = names[1]
  end

  private
  def create_thing
    @thing = Thing.new
    @thing.name = self.name
    @thing.save!
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top