.build无法分配尚不存在的外键 [英] .build can't assign foreign key that doesn't exist yet

查看:78
本文介绍了.build无法分配尚不存在的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码用于在用户控制器中为用户创建图片:

I have the following code for creating pictures for users in my users controller:

  def new
    @user = User.new
    @pictures = @user.pictures.build({:placement => "front"},{:placement => "profile"})
  end

但是,当我创建一个新用户时,它并不会自动构建位置为正面"或个人资料"的图片.实际上,图片没有任何更新.图片模型具有

However, when I create a new user, it isn't automatically building pictures with placement "front" or "profile." In fact, there's no update whatsoever to pictures. The pictures model has

attr_accessible :placement

和在picture.rb

and in picture.rb

belongs_to :user

和在user.rb

has_many :pictures
accepts_nested_attributes_for :pictures, allow_destroy: true

为什么我的构建命令无提示地失败了?

Why is my build command silently failing?

使用.save !,我了解到正在分配@pictures,但是问题是没有user_id与它们相关联.当我故意分配user_id时,如下所示:

Using .save!, I have learned that @pictures are being assigned, but the problem is no user_id being associated with them. When I intentionally assign the user_id, as in:

def new
    @user = User.new
    @pictures = @user.pictures.build({:placement => "front", :user_id => @user.id},{:placement => "profile", :user_id => @user.id})
 end

它仍然没有分配user_id.

It still does not assign a user_id.

奇怪的是,当我在Rails控制台中运行相同的命令时,它正确分配了用户名.

Strangely, when I run the very same commands in the rails console, it does correctly assign the user_id.

似乎新的@user直到运行@pictures命令后才获得分配给他的自动ID,但是控制台版本成功了,因为它按顺序执行操作.

It appears that the new @user does not get an auto id assigned to him until after the @pictures command is run, yet the console version is succeeding because it is performing the operations in sequence.

所以这就是为什么我看到一个空白的ID.

So, that's why I'm seeing a blank id.

为什么会这样?并且,这个同时进行的id分配不是模型应该使用belongs_tohas_manyaccepts_nested_attributes_for来处理的吗?

Why is this happening? And isn't this simultaneous id assignment something the model is supposed to take care of with belongs_to and has_many, and accepts_nested_attributes_for?

如果直到保存后才创建将嵌套属性链接在一起的ID,那么解决分配嵌套属性的适当方法是什么?

What is the appropriate way to address assigning nested attributes if the ID that links them together isn't created until after save?

为什么这不起作用?

推荐答案

不确定这是否是您的问题,但需要在picture.rb中的attr_acessible行中添加:user_id.您要读取/写入的所有属性都必须是attr_accessible的,否则您将得到该质量分配错误.

Not sure if this is your problem, but you need to add :user_id to your attr_acessible line in picture.rb. Any attributes you want to read/write need to be attr_accessible or you will get that mass-assignment error.

这篇关于.build无法分配尚不存在的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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