【问题标题】:rails - can't build a record with uploaded filerails - 无法使用上传的文件建立记录
【发布时间】:2013-03-28 16:01:57
【问题描述】:

我正在尝试像这样构建一个配置文件对象:

@user.profiles.build(params[:profile])

调用 build 时,它会运行 Profile 的验证,但是当上传图像并且包含在 params[:profile] 中时会出现问题

当那里有图像并调用 build 时,将运行验证并且找不到用户,因为 user_id 未传递到 proc。但是如果params[:profile]中没有图片,则传入user_id并找到用户。

我的模型:

class User < ActiveRecord::Base
  attr_accessor :require_profile_name
  has_may :profiles
end

class Profile < ActiveRecord::Base
  attr_accessor :name, :image
  belongs_to :user
  validates :name, if: Proc.new { |profile| profile.user.require_profile_name }
end

我在 google 周围没有发现有同样问题的人,所以我不知道从哪里开始。

感谢您对此的任何帮助。

【问题讨论】:

  • 只是一个更正。当您调用build 时,尚未执行任何验证。验证仅在您调用 savecreateupdate_attributes 时运行(我可能缺少其他一些方法)
  • 你是对的,但是当 build 被调用时我得到了undefined method require_profile_name for nil:NilClass。肯定不在save 上。

标签: ruby-on-rails ruby validation activerecord paperclip


【解决方案1】:

对于您的个人资料类,您需要确保在检查名称验证之前先设置用户

class Profile < ActiveRecord::Base
  attr_accessor :name, :image
  belongs_to :user
  validates :user, presence: true
  validates :name, presence: true, if: proc { |profile| profile.user.try(:require_profile_name) }
end

这样,如果没有设置用户,记录将不会被保存。如果设置了用户并且需要配置文件名称,则当名称为空时,它也会验证失败。

【讨论】:

  • 我明白你在说什么,但问题是当配置文件参数中有文件时,用户永远不会被设置,原因不明。
  • 没有其他建议?我仍然对此感到困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 2016-05-21
  • 2018-04-08
  • 2015-05-07
  • 1970-01-01
相关资源
最近更新 更多