Rails 多选形式:没有将字符串隐式转换为整数 [英] Rails multiple select form: no implicit conversion of String into Integer

查看:76
本文介绍了Rails 多选形式:没有将字符串隐式转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 4 中,为什么没有将 genre_id 数组保存到数据库中?我想是因为ids被读为字符串,当它需要保存为整数时,但过去我没有这个问题.

In Rails 4, Why isn't an array of genre_id being saved to the database? I think it's because the ids are being read as a string, when it needs to be saved as an integer, but in the past I didn't have this problem.

我在尝试发布以下内容时收到 没有将字符串隐式转换为整数 错误:

I get a no implicit conversion of String into Integer error when trying to POST the following:

    <%= form_for @project do |f| %>
    <%= select_tag 'project[genres_projects_attributes][genre_id][]',       
        options_for_select(Genre.order(:id).collect{|g| [g.name, g.id]}), 
        { include_hidden: true, multiple: true,  class: 'form-control'} %>
    <% end %>

在我的应用中,

Project has_many :genres, through: :genres_projects

我的参数如下所示:

{"utf8"=>"✓","authenticity_token"=>"[xxx]",
 "project"=>{"name"=>"sdfds",
 "genres_projects_attributes"=>{"genre_id"=>["2",
 "3",
 "4"]},
 "commit"=>"Go!"}

我的项目参数:

    def project_params
        params.require(:project).permit(:id, genres_projects_attributes: 
        [:id, {genre_id: []}, :project_id])
    end

这是我的控制器中引发错误的行:

Here's the line in my controller that's throwing the error:

def create
    @project = Project.create(project_params)
  end

推荐答案

很遗憾没有找到答案,因此采取了以下解决方法:

Unfortunately didn't find an answer so did the following workaround:

@genre_ids = project_params[:genres_projects_attributes][:genre_id]
@genre_ids.each do |g|
  GenresProject.create!(project_id: @project.id, genre_id: g)
end

更新:

我发现这是导致问题的第一个空白值.从 Rails 4.x 开始,您还可以在表单中添加 include_hidden: false.

I found out that it was the first blank value that was causing the issue. As of Rails 4.x, you can also add include_hidden: false in your form.

再次更新:

if project_params[:genres_projects_attributes]
      @project.genres.delete_all
      project_params[:genres_projects_attributes][:genre_id].each do |g|
        @project.genres << Genre.find(g)
      end
      @project.update!(project_params.except :genres_projects_attributes)
    else
    @project.update!(project_params)

这篇关于Rails 多选形式:没有将字符串隐式转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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