2016-10-18 5 views
0

Я пытаюсь вставить массив в базу данных. Я могу увидеть массив (статус «=» {«group_one» => «One»}, «group_two» => «One»}) в параметрах, но при вставке inot db он опускается.Хеш не вставлять в базу данных

Моя консоль показывает следующее:

Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"JgCBl8vcDAP9AUGaylk34om4mbKkxHCgM+GuAfxTL3sywaJkmvKL3pyS2C44MAkzMZ6AK+CUVv/Vmg9aUQYrZw==", 
"irb"=>{"proposalno"=>"", "otherapptype"=>"", "titleofproject"=>"", 
"date1"=>"", "date2"=>"", "date3"=>"", "fundingdetails"=>"", 
"fund"=>"No internal funds or external funds are requested", 
"datetobegindc"=>"", "rationale"=>"", "abstract"=>"", 
"noofsub"=>"0", "natureofassociation"=>"", 
"subjectselection"=>"", "confidentiality"=>"", 
"howwhereconsent"=>"", "methodproceduresubjectparti"=>"", 
"childrenpermission"=>"", "infowithheld"=>"", 
"riskbenefitratio"=>"", "minimizingrisk"=>""}, 
"status"=>{"group_one"=>"One", "group_two"=>"One"}, 
"responsibility"=>{"nameoffac"=>"", "nameofinv"=>"", 
"deptoffac"=>"", "deptofinv"=>"", "addoffac"=>"", 
"addofinv"=>"", "phoneoffac"=>"", "phoneofinv"=>"", 
"emailoffac"=>"", "emailofinv"=>""}, "commit"=>"SUBMIT MY DETAILS"} 
    (0.2ms) begin transaction 
    SQL (2.9ms) INSERT INTO "irbs" ("proposalno", "titleofproject", 
"date1", "date2", "date3", "fund", "fundingdetails", "datetobegindc", 
"rationale", "abstract", "noofsub", "natureofassociation", 
"subjectselection", "confidentiality", "howwhereconsent", 
"methodproceduresubjectparti", "childrenpermission", "infowithheld", 
"riskbenefitratio", "minimizingrisk", "otherapptype", "created_at", 
"updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 
?, ?, ?, ?, ?, ?) [["proposalno", ""], ["titleofproject", ""], 
["date1", ""], ["date2", ""], ["date3", ""], 
["fund", "No internal funds or external funds are requested"], 
["fundingdetails", ""], ["datetobegindc", ""], ["rationale", ""], 
["abstract", ""], ["noofsub", "0"], ["natureofassociation", ""], 
["subjectselection", ""], ["confidentiality", ""], 
["howwhereconsent", ""], ["methodproceduresubjectparti", ""], 
["childrenpermission", ""], ["infowithheld", ""], 
["riskbenefitratio", ""], ["minimizingrisk", ""], 
["otherapptype", ""], ["created_at", 2016-10-18 19:48:35 UTC], 
["updated_at", 2016-10-18 19:48:35 UTC]] 

Вот мой контроллер:

class IrbsController < ApplicationController 

    def new 
    @irb = Irb.new 
    end 



    def create 
    @irb = Irb.new(irb_params) 
    if @irb.save 
     #RegistrationMailer.signup_confirmation(@registration).deliver 
     #log_in @user 
     flash[:success] = "Your details have been registered. A confirmation email has been sent." 
     redirect_to root_url 
    else 
     render 'new' 
    end 
    end 

    def index 
    end 

    def edit 
    end 

    def show 
    end 

    private 
    def irb_params 
     params.require(:irb).permit(:proposalno, :apptype, :titleofproject, :acc1, :date1, :acc2, :date2, :acc3, :date3, :projtype, :fund, :fundingdetails, :datetobegindc, :statusofprininv, :typeofreview, :rationale, :abstract, :noofsub, :assowithsub, :natureofassociation, :subjectselection, :ressubcomp, :adforresparti, :confidentiality, :voluntaryparticipation, :howwhereconsent, :methodproceduresubjectparti, :childrenpermission, :infowithheld, :risk, :riskbenefitratio, :minimizingrisk, :otherapptype, status:[]) 
    end 
end 

Здесь миграция:

class CreateIrbs < ActiveRecord::Migration[5.0] 
    def change 
    create_table :irbs do |t| 
     t.string :proposalno 
     t.text :status 
     t.string :responsibility 
     t.string :apptype 
     t.string :titleofproject 
     t.string :acc1 
     t.string :date1 
     t.string :acc2 
     t.string :date2 
     t.string :acc3 
     t.string :date3 
     t.string :projtype 
     t.string :fund 
     t.string :fundingdetails 
     t.string :datetobegindc 
     t.string :statusofprininv 
     t.string :typeofreview 
     t.string :rationale 
     t.string :abstract 
     t.string :poputype 
     t.string :noofsub 
     t.string :assowithsub 
     t.string :natureofassociation 
     t.string :subjectselection 
     t.string :ressubcomp 
     t.string :adforresparti 
     t.string :confidentiality 
     t.string :voluntaryparticipation 
     t.string :howwhereconsent 
     t.string :methodproceduresubjectparti 
     t.string :childrenpermission 
     t.string :infowithheld 
     t.string :risk 
     t.string :riskbenefitratio 
     t.string :minimizingrisk 
     t.string :otherapptype 
     t.timestamps 
    end 
    end 
end 

Модель трески е:

class Irb < ApplicationRecord 
    serialize :status 
end 
+1

Вам нужно добавить больше деталей, прежде чем кто может помочь вам здесь –

+0

@CdotStrifeVII я добавил свой код контроллера. Пожалуйста, смотрите. – Sujith

+0

Возможно, это только я, но я не нашел массив в списке параметров. Как называется ваш массив? – spickermann

ответ

0

Вы вставляете Hash не массив здесь. Разница в коротком - хэш состоит из набора ключей и значений.

Как уже упоминалось, okomikeruko лучше определить столбец с текстовым типом данных. Хотя я не думаю, что он перехватывает 255 символов здесь, по крайней мере, в примере, указанном в вашем вопросе.

Я считаю, что проблема в вашем методе permit. Для ключа с именем :status: вы определяете 0 ключей, которые разрешены в вашем хеше. Вот отсюда и проблема.

Все, что вам нужно, это указать, следует ли указывать ключи ..., status: [:group_one, ...], если вы их знаете, или в случае, если они являются динамическими, чтобы пойти с другим решением, которое вы найдете в ссылках ниже.

https://github.com/rails/rails/issues/9454

Rails4: How to permit a hash with dynamic keys in params?

+0

Большое спасибо за ваш ответ. Я нашел небольшую ошибку, и я ее исправил. – Sujith

+0

Я рад, что это помогло. – rudkovskyi

Смежные вопросы