在Rails 4中保存嵌套模型 [英] Saving nested model in Rails 4

查看:62
本文介绍了在Rails 4中保存嵌套模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kinda是Rails的新手,有点.

Kinda new to the Rails thing, in a bit of a spot.

其中一个模型在has_many/belongs_to关联中依赖于另一个模型.

One of the models is dependent on the other in a has_many/belongs_to association.

基本上,在我的应用程序上创建帖子"时,用户还可以附加图像".理想情况下,这是两个单独的模型.当用户选择照片时,一些JavaScript会将其上传到Cloudinary,并且返回的数据(ID,宽度,高度等)将以JSON字符串化并设置在隐藏字段中.

Basically, when creating a "Post" on my application, a user can also attach "Images". Ideally these are two separate models. When a user chooses a photo, some JavaScript uploads it to Cloudinary and the returned data (ID, width, height, etc) are JSON stringified and set on 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)

当然,这种关系存在于我的Post模型中

And of course, the relationship exists in my Post model

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

和我的图片模型

belongs_to :post

我迷路的是如何处理Post控制器的create方法上的序列化图像数据?简单地解析JSON并保存它并不会在保存时创建带有数据的Image模型(而且感觉不正确):

Where I'm lost is what to do with the serialized image data on the Post controller's create method? Simply parsing the JSON and saving it doesn't create the Image models with the data upon saving (and doesn't feel right):

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

所有这些最终都归结为以下参数:

All of this essentially culminates to something like the following parameters:

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

整个过程似乎有些费解-现在我该怎么办?首先有没有更好的方法来做我想做的事情? (这样的嵌套属性也需要强参数吗?)

This whole process seems a little convoluted -- What do I do now, and is there a better way to do what I'm trying to do in the first place? (Also are strong parameters required for nested attributes like this...?)

这时我得到了这个错误:

At this point I got this error:

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

来自这一行...

@post = current_user.reviews.new(post_params)

似乎不是从嵌套属性创建图像,而是可以预期的. (无论是否存在:autosave,都会发生同样的事情.)

Seems like it's not creating the images from the nested attributes but it's expected to. (The same thing happens when :autosave is there or not).

推荐答案

该ActionController :: Parameters错误出现了此问题.您需要确保您在posts_controller中允许所有必要的参数,如下所示:

Just had this issue with that ActionController::Parameters error. You need to make sure you're permitting all the necessary parameters in your posts_controller, like so:

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

确保允许使用image.id属性非常重要.

It's important to make sure you're permitting the image.id attribute.

这篇关于在Rails 4中保存嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆