Rails 4 render action => new不会经历新动作

时间:2015-03-03 17:32:56

标签: ruby-on-rails

我最常见的是rails代码

def new
  @company = Company.new
  @companies = Company.order(:name).pluck(:name, :id)
end

def create
  @company = Company.find(params["company"]["id"]) rescue nil
  unless @company
    render action: 'new'
    return
  end

status = @company.update_attributes(total_licenses: params["company"]["total_licenses"].to_i, assigned_licenses: 0)
if status == true 
    redirect_to users_super_admin_index_path, flash: {notice: "License has been allocated to company."}
else
    render action: 'new'
end
end

但是当出现错误时,它应该将动作渲染为新的,但它会直接渲染模板,因此@company仍为零并抛出错误

ActionView :: Template :: Error(表单中的第一个参数不能包含nil或为空)

我想找到永久和正确的解决方案,请不要乱砍:)。我之所以遇到这个问题。

在我看来 -

<%= form_for @company, url: licenses_path, method: "post" do |f| %>
<%= f.label :id, 'Select Company' %><br/>
<%= f.select :id, @companies, :include_blank => "Select Company", required: true %><br/><br/>

<%= f.label :total_licenses, 'License' %><br/>
<%= f.text_field :total_licenses, required: true%><br/><br/>

<%= f.submit 'Assign'%>
<% end %>

1 个答案:

答案 0 :(得分:1)

请记住,render(action: ...)实际上并没有运行相关方法,它只是渲染模板。您需要手动触发new方法才能执行此操作。