This time, when I tried to use "file_field" in "fields_for", it was not reflected in the view and I had a hard time, so I will describe how to solve it as a memorandum. I hope it will help those who have the same problems.
・ (Parent) post model ・ (Child) image model
We associate with post model and image model accepts_nested_attributes_for.
Create SNS like Twitter and FB. I am about to create a post form using "form_for".
Sentence → post model Photo → image model I wanted to save it in, and created a view like this:
(Only the relevant parts are excerpted for easy understanding)
haml
.form__contents
= form_for @post, id: "new_post" do |f|
.title
= f.text_field :title
.text
= f.text_area :text
.image
= f.fields_for :images do |i|
= i.file_field :image
= f.submit "Post!"
Alright, coding is complete! !! Let's go to the view! !! …that,,"= f.fields_for :images do |i|The following is not reflected ... Moreover, I don't know what's wrong because there are no errors ... I did as I checked ...
haml
.form__contents
= form_for @post, id: "new_post" do |f|
.title
= f.text_field :title
.text
= f.text_area :text
.image
= f.fields_for :images, @post.images.build do |i|
= i.file_field :image
= f.submit "Post!"
I just thought that if you write the model you want to save in "fields_for", it will be saved in the column described in "file_field".
It seemed that I had to pass ** an instance of the child model ** to the second argument of "fields_for".
I see ... It's natural because I'm giving an instance to "form_for" as well. (In the first place, I knew for the first time that I could create an instance of images.build!)
More and more.
Recommended Posts