开发者

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 开发者_如何学Goon the page...


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".


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜