簡體   English   中英

Rails 4.2.x-在模型中使用params哈希數據

[英]Rails 4.2.x - use params hash data in model

問題 -有沒有辦法將params哈希數據傳遞/使用到關聯的模型?

我的應用程序要點:

  1. Image模型belongs_to User模型, User模型has_many Image實例。
  2. Image架構:

    create_table“ images”,強制::cascade do | t | t.string“文件名” t.string“ mime_type” t.binary“內容” t.integer“ user_id” t.datetime“ created_at”,null:假t.datetime“ updated_at”,null:假結束

    add_index“ images”,[“ user_id”],名稱:“ 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模型中正確傳遞顯式參數哈希-NO GO
  • create動作中定義實例@params_hash = params [:image] [:uploaded_file](單獨或從自定義類方法內部)-否
  • controller#action定義常量-不能執行

什么有效? 全局變量- $variable

這是一種Rails方式嗎? ->查詢要建模的數據

在一個好的MVC應用程序中,您的模型應該不知道參數,請求或任何直接的用戶輸入。 該模型僅從控制器獲取數據,並執行業務邏輯並保留數據。

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

模型代碼似乎是正確的,這只是您嘗試將圖像數據獲取到模型中的方法所違反的。 通常,您將在控制器中創建一個新的Image實例,然后設置圖像數據,如下所示:

image = user.images.new # If "user" is set to the correct user for the image
image.uploaded_file = params[:image][:uploaded_image]
# ...whatever else you need to do with the image here
image.save

這是一個准系統控制器的操作,因此您將要確保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

因此,您要將mime_type設置為文件的content_type。

你為什么不做

def mime_type
  correct_mime = ["image/jpeg", "image/png", "image/gif"]
  unless correct_mime.include? mime_type.chomp
    errors.add(:base, 'must be .jpeg, .png or .gif')
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM