I have a form that is using 2 models. Person and Address. Itâ€™s a one-to-one association via polymorphism.
class Person < ActiveRecord::Base
has_one :address, :as => :addressable, :dependent => :destroy
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
On my form, when a Person is created, it automatically creates an Address, even though the address fields were not filled in.
In my PersonController create method, I want to verify that an Address has not be submitted. How can I do that?
@person = Person.new
def create @person = Person.new(params[:person]) @person.address = Address.new(params[:address]) @person.save
I want to add an condition statement that checks to see if params[:address] is empty, but the array always comes back populated, but the attributes are empty. Soâ€¦how can I check that. Something also tells me I might be doing something wrong or missing something.
check the contents for params[:address]
provide code if possible,from where you are accepting values ...
Rather than checking the params of the create request, you should add validations to your models that reflect which fields you require. In this case I image you'd want to use #validates_presence_of for fields you require, and possibly #validates_format_of if you want to check for valid postal codes or the like.
Also, I'd suggest you take a look at nested attribute assignment, which is available as of Rails 2.3. If you set that up correctly you'll need to create only the person model, and ActiveRecord will create the associated address model for you, based on the nested attributes.
Both of these suggestions will help you push your logic into the models, keeping your controllers nice and skinny and avoiding the need to duplicate code should you end up creating Person or Address models elsewhere.