Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Checking for Empty Arrary...really empty Attributes
3 Posts
Checking for Empty Arrary...really empty Attributes

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

end

class Address < ActiveRecord::Base

belongs_to :addressable, :polymorphic => true

end

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?

def new

@person = Person.new

end

def create @person = Person.new(params[:person]) @person.address = Address.new(params[:address]) @person.save

end

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.

Hello

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.

3 Posts
Login to add your message