Rails - Passing Arrays as Params in Model Function

2019-08-30 01:23发布

for_tag has two attributes, 1: :level_id 2: :title. User is entering both values but in :title, entering values as

Math,English,ETC and am splitting this into array as

@test = params.requrie(:service).permit(:title)[:title]

I need to create entering in DB with the same :level_id

title:math,level_id:1
title:English,level_id:1

in my Service Controller am trying this.

def create
    @qure = params.require(:service).permit(:level_id)[:level_id]
    @test = params.require(:service).permit(:title)[:title]
    @gain = @test.split(",")

    @gain.each do |fil|
      Service.new(fil,@qure)
    end

    redirect_to root_url
  end

this giving me an error

When assigning attributes, you must pass a hash as an argument.

my Migration

def change
    create_table :services do |t|
      t.string :title
      t.integer :level_id

      t.timestamps null: false
    end
  end

1条回答
你好瞎i
2楼-- · 2019-08-30 01:58

You can just do the following:

@test = params.require(:service).permit(:title)[:title]

def create
  @qure = params.require(:service).permit(:level_id)[:level_id]
  @test = params.require(:service).permit(:title)[:title]
  @gain = @test.split(",")

  # Note: You need to use a hash to pass args to the model
  @gain.each do |fil|
    Service.create!(title: fil, level_id: @qure)
  end

  redirect_to root_url
end

I've also used create! in the method but you should consider using save and checking the return value if you want to use validations. The above will raise an error if there are validation issues.

查看更多
登录 后发表回答