Difficulty using collection_check_boxes

2019-08-12 12:34发布

问题:

I have a model Project which has many ProjectGenres which references Genres:

class Project < ActiveRecord::Base
  has_many :project_genres
  accepts_nested_attributes_for :project_genres, allow_destroy: true
  has_many :genres, through: :project_genres
end

class ProjectGenre < ActiveRecord::Base
  belongs_to :project
  belongs_to :genre
end

class Genre < ActiveRecord::Base
  has_many :project_genres
  has_many :projects, through: :project_genres
end

When I create a project, I want to tick the appropriate genres it affiliates with. Then when they submit this form, it should create the appropriate records in the ProjectGenre table.

I have the following line in my form:

<%= f.collection_check_boxes(:project_genres, Genre.all, :id, :description) %>

I'm not really sure what I do in the controller though? I get an array passed back in params[:project][:project_genres] (although it passes back an extra empty entry), but am I supposed to do the donkey work here in creating the embedded objects myself, or am I missing something to be able to just create these automatically?

回答1:

I'm not a rails expert but maybe i can help.

Try changing the helper to look like this.

<%= f.collection_check_boxes(:genres_ids, Genre.all, :id, :description) %>

Then in the controller

def create
  @project = Project.new(project_params)

  respond_to do |format|
    if @project.save
      format.html { redirect_to @project , notice: 'Project was successfully created.' }
    else
      format.html { render action: 'new' }
    end
  end
end

And you have to permit genres_ids if you are using Rails 4 or the strong_params gem

#I will asume Project model has a name attribute
def project_params
  params.require(:project).permit(:name, :genres_ids => [])
end

I think you don't need to use the accepts_nested_attributes_for when you are are using the collection_check_boxes helper.



回答2:

You would really need to post more code of your form are you using form_for like...

<%= form_for @project do |f| %>
    ...
<% end %>

<%= f.fields_for :genres do |builder| %>
    <%= render "genre_fields", :f => builder %>
 <% end %>

as this may solve the issue. Post more of your form code maybe