問題描述
rails ‑ không thể tạo bản ghi với tệp đã tải lên (rails ‑ can't build a record with uploaded file)
I am trying to build a profile object like so:
@user.profiles.build(params[:profile])
When build is called, it runs the validations for Profile
but the issue occurs when there is an image uploaded and when it is contained in params[:profile]
When there is an image there and build is called, the validations are run and it cannot find a user because the user_id is not passed into the proc. But if there is no image in params[:profile]
the user_id is passed in and it finds a user.
My models:
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
I have found no one with the same problem looking around google, so I am at a loss about where to start.
Thanks for any help with this.
參考解法
方法 1:
for your profile class, you need to make sure that the user is set first before you check for the validation of the name
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
With this, the record wont be saved if the user is not set. If the user is set and requires a profile name, it will also fail the validation when name is blank.