2014-02-10 25 views
0

我有一个设计“编辑用户”窗体在我的Rails应用程序。用户还包含school_id。在我的编辑用户表单中,我有一个部分显示用户订阅的学校。在学校名称旁边,我有一个按钮,将用户的school_id设置为零。但是,由于这实际上是一个带有隐藏字段的表单,因此用户可以在编辑用户表单上“保存更改”,并且将由于我在页面上具有的其他表单而将school_id设置为零。窗体在Rails中的形式?

伪代码:

edit user information 
School: schoolname [button to remove school] 
edit more user information 
[Submit changes] 

按钮来删除学校:

<% if current_user.school %>School: <b><%=link_to current_user.school.name, current_user.school %></b> 
    <%= form_for(@user) do |f| %> 
     <%= f.hidden_field(:school_id, :value => nil) %>    
     <%= f.submit "Remove school", class: "btn btn-danger btn-small" %> 
    <% end %> 

有没有办法实现这一目标,而无需移动删除按钮学校的形式外?它非常适合工作流程,但由于它现在在技术上属于编辑设计用户注册表格的一部分,所以会引起问题。有任何想法吗?

谢谢!

+0

你可以看看这篇文章http://weblog.rubyonrails.org/2009/1/26/nested -model-forms/ – Rinku

+0

即使我仍然只更新一个模型,嵌套窗体在这里工作吗?我只用两种形式更新用户模型。 – winston

+1

你不应该嵌套窗体 - http://stackoverflow.com/questions/379610/can-you-nest-html-forms – bridiver

回答

1

您可以通过控制器中的操作来实现它。

例如鉴于:

<%= link_to 'Remove school', user_path(@current_user), :method => :delete, :class => "btn btn-danger btn-small" %> 

在控制器:

def destroy 
    @current_user.update_attribute(:value, nil) 
    respond_to do |format| 
     format.html{redirect_to :back} 
    end 
end 
+0

谢谢!这很好用! – winston