Element belongs to Form

Hi,

You are welcome to comment on every aspect of this post – not just the core question at the bottom.

My application renders forms previously stored in the database. A Form consists of Elements:

t.references :form,

:comment => ‘What form we belong to.’

t.decimal :ordering,

:comment => ‘In what order we should appear.’

t.string :name,

:null => false,

:comment => ‘Name.’

t.string :title,

:comment => ‘Title.’

t.string :ml_type,

:null => false,

:comment => ‘Markup language type.’

t.text :value,

:null => false,

:comment => ‘Value.’

t.text :flags, :comment => ‘Flags.’

ml_type could be ‘text’, ‘select’ or any other HTML form type.

Models:

class Element < ActiveRecord::Base

Relationships

belongs_to :form

Validations

validates_numericality_of :ordering

validates_presence_of :name

end

class Form < ActiveRecord::Base

has_many :elements

end

An Element should never be orphaned (i.e. without a Form). So if you want to add an Element, you go to

http://localhost:3000/forms/1

… which shows a Form’s name with its Elements.

At the bottom of the Forms#show page I have a link ‘New Element’ which links to:

http://localhost:3000/elements/new?form_id=1

Problem here is that if you click Create and validation doesn’t pass, it forgets about the form_id parameter.

How can I make it remember the form_id?

Best regards,

CmdJohn

You can store the form_id in a hidden field (hidden_field_tag).

That value will come back in the params hash, to be retrieved and re-used in your else case when validation fails in the create method for element.

Thanks, that worked.

What’s the difference between hidden_field and hidden_field_tag?