0

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 %>

In my app,

Project has_many :genres, through: :genres_projects

My parameters look like this:

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

My project_params:

    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
allenwlee
  • 665
  • 6
  • 21
  • do you have an id for project based upon params coming in? what do you get when you do `project = Project.create!(project_params)` (note the exclamation point) from rails console passing in your params? – timpone Mar 03 '14 at 06:56
  • no, there is no id for the project coming in. – allenwlee Mar 03 '14 at 18:18

1 Answers1

0

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

UPDATE:

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.

UPDATE AGAIN:

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)
allenwlee
  • 665
  • 6
  • 21