Reputation: 14504
I want create multiple Indhold in Indhold model. But when I submit I only get 1 Indhold parameter and it create only 1 indhold, even if i have checked several checkboxes . I want it to create new Indhold width those Check Checkboxes. My indhold form:
<%= form_tag({:action => 'create'}, {:multipart => true} ) %>
<% for indhold in Indhold.find(:all) %>
<%= check_box_tag( "indholds[navn]", indhold.navn ) %>
<%= indhold.navn %><br />
<% end %>
</div>
<div class="actions">
<%= submit_tag( "Submit" ) %>
</div>
My indhold controller:
def new
@indhold = Indhold.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @indhold }
end
end
def create
@indhold = Indhold.new(params[:indhold])
respond_to do |format|
if @indhold.save
format.html { redirect_to(@indhold, :notice => 'Indhold was successfully created.') }
format.xml { render :xml => @indhold, :status => :created, :location => @indhold }
else
format.html { render :action => "new" }
format.xml { render :xml => @indhold.errors, :status => :unprocessable_entity }
end
end
Best regards, Rails beginner
Upvotes: 1
Views: 1710
Reputation: 13724
First, change indholds[navn] to indholds[navn][] in the checkbox tag. That will send multiple values to params. But Indhold.new is going to create only one new record. You would have to do something like this to create multiple records:
@indholds = []
@errors = []
params[:indhold][:navn].each do |navn|
indhold = Indold.new(:navn => navn)
if indhold.valid?
@indholds << indhold.save
else
@errors += indhold.errors
end
end
It's not really a standard use of new; I would change the action to multiple_new or similar. You'll also have to use @errors instead of @indhold.errors in the form.
Upvotes: 2