2010-12-19 77 views
1

我想在Indhold模型中创建多个Indhold。但是当我提交时,我只能得到1个Indhold参数,并且它只创建1个内容,即使我已经选中了几个复选框。 我希望它创建新的Indhold宽度那些检查复选框。 我indhold形式:Rails如何使用复选框创建多个对象

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

我indhold控制器:

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 

此致 滑轨初学

+0

看起来你正试图创建一个包含来自现有Indholds的儿童navn值的Indhold,但Indhold.navn似乎并不是has_many--这是否正确?你可以添加Indhold模型的代码吗? – 2010-12-19 18:27:37

+0

我不是想创建一个包含儿童navwin的Indhold。我正在尝试从indhold模型创建多个Indholds宽度复选框。 – 2010-12-19 18:42:11

回答

2

首先,变化indholds [navn],在复选框indholds [navn] []标签。这将发送多个参数值。但Indhold.new将创造只有一个新的纪录。你将不得不这样做来创建多条记录:

@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 

这不是真正的新标准使用;我会改变行动multiple_new或类似。您还必须在表单中使用@errors而不是@ indhold.errors。

+1

我得到一个没有方法的错误。你能告诉我有表格和控制器应该看起来像吗? – 2010-12-19 21:53:36