【发布时间】:2016-02-11 07:49:04
【问题描述】:
问题 - 有没有办法将params 哈希数据传递/使用到关联模型?
我的应用的要点:
-
Image模型belongs_toUser模型,User模型has_manyImage实例。 -
Image架构:create_table "images", force: :cascade do |t| t.string "文件名" t.string "mime_type" t.binary “内容” t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false 结束
add_index "images", ["user_id"], name: "index_images_on_user_id"
-
在 root_url(即
StaticPagesController#home)我有图片上传表单: -
在
Image我做的模型中:def uploaded_file=(initial_data) self.filename = initial_data.original_filename self.mime_type = initial_data.content_type self.content = initial_data.read initial_data.rewind end -
也是自定义验证:
validate :mime_type
与
def mime_type
correct_mime = ["image/jpeg", "image/png", "image/gif"]
unless correct_mime.include? params[:image][:uploaded_file].content_type.chomp
errors.add(:base, 'must be .jpeg, .png or .gif')
end
end
- 众所周知,来自上传表单的所有查询都会转到 params[:image][:uploaded_file]
6.是否可以将 params[:image][:uploaded_file] 作为具有原始哈希结构的哈希传递给 Image 模型?
我已经尝试过,但没有一个有效:
- 在
Image模型中传递显式参数哈希 - 不可行 - 在
create操作中定义实例@params_hash = params[:image][:uploaded_file](单独或从自定义类方法内部) - 不行 - 在
controller#action中定义常量 - 不行
什么有效?
全局变量 - $variable
这是一种轨道方式吗? -> 查询数据到模型
【问题讨论】:
-
为什么不能使用
mime_type而不是params[:image][:uploaded_file].content_type?除非我遗漏了一些明显的东西? -
次要问题(本例)是如何从模型中的 params hash 中提取上传的文件 content_type,主要问题是 - 如何在适当的模型中为未来的应用正确使用 params hash。
-
@japed - 您能否将它作为您所建议的答案提出来。谢谢!
标签: ruby-on-rails model params