Rails - 在模型函数中将数组作为参数传递 [英] Rails - Passing Arrays as Params in Model Function

查看:49
本文介绍了Rails - 在模型函数中将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for_tag 有两个属性,1::level_id 2::title.用户正在输入两个值,但在 :title 中,输入值作为

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]

我需要使用相同的 :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

这给了我一个错误

分配属性时,必须传递一个哈希值作为参数.

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

我的迁移

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

      t.timestamps null: false
    end
  end

推荐答案

您只需执行以下操作:

@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.

这篇关于Rails - 在模型函数中将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆