gpt4 book ai didi

ruby-on-rails - Rails 4.2.x - 在模型中使用参数散列数据

转载 作者:行者123 更新时间:2023-12-04 03:45:09 25 4
gpt4 key购买 nike

问题 - 有没有办法将params哈希数据传递/使用到相关模型?

我的应用程序的要点:

  1. Image 模型 belongs_to User 模型,User 模型 has_many 图片实例。
  2. 图片 架构:

    create_table“图像”,强制::级联做|t| t.string "文件名" t.string "mime_type" t.binary“内容” t.整数“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"

  3. 在 root_url(即 StaticPagesController#home)中,我有图片上传表单:

  4. 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
  5. 还有一个自定义验证:

    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
  1. 众所周知,来自上传表单的所有查询都会转到 params[:image][:uploaded_file]

6.是否可以将 params[:image][:uploaded_file] 作为具有原始哈希结构的哈希传递给 Image 模型?

我试过但没有一个有效:

  • Image 模型中直接传递显式参数哈希 - 不行
  • create 操作中定义实例 @params_hash = params[:image][:uploaded_file](单独或从自定义类方法内部定义)- 不行
  • controller#action 中定义常量 - 不行

什么有用??全局变量 - $variable

这是一种 Rails 方法吗? -> 查询数据到模型

最佳答案

在一个好的 MVC 应用程序中,您的模型不应该知道参数、请求或任何直接的用户输入。该模型只是从 Controller 获取数据并执行业务逻辑并持久保存数据。

class Image < ActiveRecord::Base
belongs_to :user
validates_inclusion_of :mime_type,
in: ["image/jpeg", "image/png", "image/gif"],
message: 'must be .jpeg, .png or .gif'
end

class ImagesController < ApplicationController

def new
@image = Image.new
end

def create
@image = Image.new(
filename: image_params.original_filename
mime_type: image_params.content_type,
content: image_params.read
)
if @image.save
redirect_to root_path
else
render :new
end
end

private
def image_params
params.require(:image).require(:uploaded_image)
end
end

关于ruby-on-rails - Rails 4.2.x - 在模型中使用参数散列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com