开发者

Rails 3 accepts_nested_attributes_for form for new model (instead of full collection)

开发者 https://www.devze.com 2023-02-15 00:30 出处:网络
I have a model Album which has a \"has_many :trough\" assocation named Track. Basically, an album can have a number of tracks on it, but a track can belong to more than one album at the same time (hen

I have a model Album which has a "has_many :trough" assocation named Track. Basically, an album can have a number of tracks on it, but a track can belong to more than one album at the same time (hence the through association "Tracklist").

I have a RESTful app with a form (with the help of formtastic) that puts out all the tracks's attributes like so

form.semantic_fields_for :tracks do | builder |
    builder.fields
end

The form puts out all the associated Tracks' fields and I can update them fine, everything works.

Now, what I want to do is have another view to add a new track to an existing album. In this view, I don't want to render all the input fields for the existing tracks, but only the fields for the single new association I am trying to create.

I have tried to find info on how to do this, and the best I've come up with is:

form.semantic_fields_for :tracks, Track.new do | builder | 
    builder.fields
end

This outputs a single s开发者_如何学编程et of Track inputs, like needed, and I can submit the form and the track gets created and associated to the product - but only if there are no validation errors.

The problem comes with validations. If one fails, the app renders the same view again, but all the inputs are empty again (all data, valid or not, is lost, and the inline error messages for Formtastic are also gone):

 form.semantic_fields_for :tracks, Track.new do | builder | 
        builder.fields
 end

I reckon this is because I do a Track.new even though there is already an object in the request params which has the data and error messages. This is no good of course. What I want to have is the form for the single track displayed with the already input data, as well as the Formtastic error messages.

What am I doing wrong?


Instead of

Track.new

you need to set up

@track = @album.tracks.build

in your controller and use that. That should preserve the fields through the validation errors.


I found a solution. It works, but I wonder if it is a good solution. Thanks Srdjan for putting me on the right track!

@track = @album.tracks.build

form.semantic_fields_for :tracks, @track do | builder | 
   builder.fields if builder.object.new_record?
end

Apparently only renders the new record's form fields.

0

精彩评论

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