【问题标题】:form_for not working rails 4.0form_for 不工作 rails 4.0
【发布时间】:2014-09-05 02:04:36
【问题描述】:

我在 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

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

views/contacts/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>

请帮忙...谢谢!!!

【问题讨论】:

  • 您需要在 new 操作中定义 @opportunity 实例变量,这将呈现您的 new.html.erb

标签: ruby-on-rails forms


【解决方案1】:

将您的新操作更改为:

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

你的表格将是:

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

【讨论】:

  • 嗨 - 我试过了,得到“表单中的第一个参数不能包含 nil 或为空”,代码的第一行突出显示...@mandeep
  • @user1547174 这个错误告诉我们,无论是机会还是形式上的联系都是零。我的回答有错别字。尝试更新答案
  • @user1547174 你能发布你的日志和完整的错误吗?
  • 为什么需要在 form_for 中包含“@opportunity”?事实上你只改变了联系方式,对吧?所以,你只需要'form_for @contact'。
  • @PeterTretyakov 问题说`我有一个名为 Opportunity 的模型,它有一个名为 Contact 的嵌套资源。` 所以 [@opportunity, @contact] 为联系人控制器中的 create 方法制定了正确的路线。如果它不是嵌套的,那么 form_for @contact 会这样做:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多