【发布时间】: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