form_for not working rails 4.0

时间:2014-09-04 17:15:11

标签: ruby-on-rails forms

我在rails中有一个简单的form_for,点击“添加”后不会创建新记录。我有一个名为Opportunity的模型,它有一个名为Contact的嵌套资源。联系表格是我遇到的问题。我将我的表单与可用的类似嵌套资源进行了比较,但无法找到问题。这是我的代码:

联系人控制器:

  def new
    @contact = Contact.new
  end


  def create

  @opportunity = Opportunity.find(params[:opportunity_id])
  @contact = @opportunity.contacts.new(contact_params)
    if @contact.save
      redirect_to @opportunity, notice: 'Contact has been added'
    else
      redirect_to @opportunity, alert: 'Unable to add Contact'
    end
  end

def contact_params
  params.require(:contact).permit(:first_name)
end

这是我遇到问题的具体表格:

视图/联系人/ new.html.erb:

    <div id="new_contact_form">

    <%= form_for ([@opportunity, @opportunity.contacts.new]) do |f| %>
        <div class="field">
            <%= f.label "Contact Info:" %> <br />
            <%= f.text_area :first_name %> 
        </div>

        <div class="actions">
            <%= f.submit 'Add' %> 
        </div>
    <% end %>

    </div>

请帮忙......谢谢!!!

1 个答案:

答案 0 :(得分:1)

将您的新操作更改为:

def new
  @opportunity = Opportunity.find(params[:opportunity_id])
  @contact = @opportunity.contacts.build
end

,您的表单将是:

<%= form_for ([@opportunity, @contact]) do |f| %>
  // form fields
<% end %>