在Rails 4中保存嵌套模型

有点像Rails的新东西,有点像。

其中一个模型依赖于has_many / belongs_to关联中的另一个。

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

# 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模型中

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

和我的图像模型

 belongs_to :post 

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

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

所有这些基本上都达到了以下参数:

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

整个过程看起来有点复杂 – 我现在该怎么做,是否有更好的方法来做我想做的事情? (这也是嵌套属性所需的强参数……?)

编辑:

此时我收到了这个错误:

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

来自这条线……

 @post = current_user.reviews.new(post_params) 

似乎它不是从嵌套属性创建图像,但它是预期的。 (同样的事情发生在:自动保存是否存在)。

刚刚遇到ActionController :: Parameters错误的问题。 您需要确保在posts_controller中允许所有必要的参数,如下所示:

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

确保您允许image.id属性非常重要。

你必须建立这样的参数:

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

您需要在images的键名称上使用*_attributes

accepts_nested_attributes_for应该为您照顾。 所以做一个Post.create(params[:post])也应该处理嵌套的图像属性。 可能出现的问题是您没有在has_many关系上指定autosave 。 所以你可能想看看这是否有所不同:

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

保存post时,这也应该保存图像。