Cjmarkham
Cjmarkham

Reputation: 9681

Rails fields_for with empty model data

I am using fields_for like so (pseudo code)

fields_for(@model) do |f|
  f.text_field :foo
end

The problem is that sometimes foo contains the model data and sometimes it doesn't, which throws an error.

undefined method 'model_name' for NilClass:Class

Is there any way around this?

Upvotes: 0

Views: 222

Answers (1)

BroiSatse
BroiSatse

Reputation: 44675

if @model
  fields_for(@model) do |f|
    f.text_field :foo
  end
end

EDIT:

Or (this however should be done in the controller)

fields_for(@model || Model.new) do |f|
  f.text_field :foo
end

Upvotes: 1

Related Questions