Rails-如何一次创建3条以上的记录

时间:2018-10-25 08:48:53

标签: ruby-on-rails ruby

我试图在Rails的数据库中创建3次或3次以上的记录。但是这里会发生此错误。

  

#<#:0x00007fc9549651c0>的未定义局部变量或方法'候选'   你的意思是? @候选人

app / views / candidates / new.html.erb

            <%= form_tag candidates_path, method: :put do %>
                <% 3.times do %>
                    <%= fields_for "candidates[]", candidate do |f| %>
                        <div class="candidate-item">    
                            <%= f.hidden_field :title_id, value: @title.id %>
                            <div class="field">
                                <label>Name</label>
                                <%= f.text_field :name, placeholder: "例)" %>
                            </div>
                            <div class="field file-field">
                                <label>Image</label>
                                <%= f.file_field :image, :type => "file" %> 
                            </div>
                        </div>
                    <% end %>
                <% end %>
                <div class="form-btn">
                    <%= f.submit "Create" %>
                </div>           
            <% end %>

app / controllers / candidates_controller.rb

def new
    @title = Title.find(params[:id])
    if user_signed_in?
        @candidate = Candidate.new
    else
        flash[:alert] = "Please login"
        redirect_to title_path(id: @title.id)
    end
end

def create
    5.times do 
        @candidate = Candidate.create(create_params)
        if @candidate.save
            flash[:success] = "Success"
            redirect_to new_candidate_path(id: @candidate.title_id)
        else
            flash[:alert] = "Failed"
            redirect_to new_candidate_path(id: @candidate.title_id)
        end
        binding.pry
    end
end

1 个答案:

答案 0 :(得分:0)

我可以用cocoon宝石来获得它。谢谢