QUESTION - is there a way to pass/use params
hash data to the associated model?
Essentials of my app:
Image
modelbelongs_to
User
model,User
modelhas_many
Image
instances.Image
schema:create_table "images", force: :cascade do |t| t.string "filename" t.string "mime_type" t.binary "content" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
add_index "images", ["user_id"], name: "index_images_on_user_id"
In root_url (which is
StaticPagesController#home
) I have image upload form:in
Image
model I do: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
Also a custom validation:
validate :mime_type
with
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
- As it is known all query from upload form goes to params[:image][:uploaded_file]
6. Is it possible to pass params[:image][:uploaded_file] to Image
model as a hash with original hash structure?
What I have tried and none of them works:
- pass explicit params hash right in
Image
model - NO GO - define instance @params_hash = params[:image][:uploaded_file] in
create
action (separately or from inside the custom class method) - NO GO - Define constant in
controller#action
- NO GO
WHAT works??
Global variable - $variable
Is it a rails way to do that? -> query data to model
mime_type
instead ofparams[:image][:uploaded_file].content_type
? Unless I'm missing something obvious? – j-dexx