Saving a nested model in Rails 4

Something new for Rails stuff, in a small place.

One of the models depends on the other in the has_many / belongs_to association.

In principle, when creating Mail in my application, the user can also attach Images. Ideally, these are two separate models. When the user selects a photo, some JavaScript uploads it to Cloudinary, and the returned data (ID, width, height, etc.) is built by JSON and set in a hidden field.

# The HTML = f.hidden_field :images, :multiple => true, :class => "image-data" # Set our image data on the hidden field to be parsed by the server $(".image-data").val JSON.stringify(images) 

And of course, relationships exist in my Post model

 has_many :images, :dependent => :destroy accepts_nested_attributes_for :images 

and my image model

 belongs_to :post 

Where am I lost what to do with serialized image data in the method of creating a Post controller? Just by analyzing JSON and saving it, it does not create image models with data when saving (and does not feel good):

 params[:post][:images] = JSON.parse(params[:post][:images]) 

All this essentially ends with roughly the following parameters:

 {"post": {"title": "", "content": "", ..., "images": [{ "public_id": "", "bytes": 12345, "format": "jpg"}, { ..another image ... }]}} 

This whole process seems a bit confusing - what should I do now, and is there a better way to do what I'm trying to do first? (There are also strong parameters needed for nested attributes like ...?)

EDIT:

At this moment, I got this error:

 Image(#91891690) expected, got ActionController::Parameters(#83350730) 

coming from this line ...

 @post = current_user.reviews.new(post_params) 

It doesn't seem like it is creating images from nested attributes, but it was expected. (The same thing happens when: autosave is there or not).

+6
source share
3 answers

This problem had a problem with this ActionController :: Parameters error. You need to make sure that you allow all the necessary parameters in your post_controller, for example:

 def post_params params.fetch(:post).permit(:title, :content, images_attributes: [:id, :public_id, :bytes, :format]) end 

It is important to make sure that you enable the image.id attribute.

+6
source

You should generate the parameters as follows:

 params[:post][:images_attributes] = { ... } 

You need *_attributes by the name of the key images .

+1
source

accepts_nested_attributes_for should take care of this for you. Thus, the execution of Post.create(params[:post]) should also take into account the attributes of the attached images. What might be wrong is that you did not point autosave to has_many. So you can see if this matters:

 has_many :images, :dependent => :destroy, :autosave => true 

It should also save images when saving a message.

0
source

Source: https://habr.com/ru/post/949125/


All Articles