Filip Stefansson
Filip Stefansson

Reputation: 211

Populate a form with the new()-method

Problem solved. HTML5 localStorage messed with me.

I'm trying to populate a form with parameters from the new()-method, and I can't get it to work.

Every user has default values for the form saved in the database(in a table called defaults), and when you create a new record I want it to be populated with the values from that table.

@default = Default.find_by_user_id(current_user.id)
@invoice = Invoice.new(:title => @default.title, :company_information => @default.company_information)

render 'create'

and then in my view:

form_for @invoice, :url => { :action => "create"} do |f| ...

What happens is that the values that are default for invoice are created, but not the ones created in the new()-method.

The weirdest part is that when I check the source code after the page is loaded, the inputs value attributes is filled with the correct information, but not rendered on the page...

Upvotes: 0

Views: 283

Answers (2)

brettish
brettish

Reputation: 2638

Strange, I don't see anything wrong with what you are trying to do... maybe something on the browser side (javascript, css, etc) is fowling things up?

Check to see if there is something selectable inside the form inputs or try creating a vanilla form without any javascript or css. Or, you might even try simply printing the contents of the attribute in the html (without using input/textarea tags) using something like:

<%= @invoice.title %>

This will at least help confirm that the default values where indeed set. Additionally, using:

<%= f.object.title %> # place me inside the form_for block

will help you confirm that the form builder instance also has the correct value.

Good luck.

Upvotes: 0

coreyward
coreyward

Reputation: 80041

What you're doing here:

Invoice.new(:title => @default.title, :company_information => @default.company_information)

Makes sense and should work…unless those fields are protected from mass assignment.

class Invoice << ActiveRecord::Base
  attr_accessible :some, :other, :fields
  ...
end

This would allow you to set :some, :other, (and) :fields when you initialize your Invoice object, but it will prevent you from setting any other "attributes".

Upvotes: 1

Related Questions