Rails-更新单个属性:使用自定义操作链接还是使用隐藏字段链接表单? [英] Rails - Update a single attribute : link with custom action or form with hidden fields?
问题描述
假设我有一个用户模型,其中的facebook_uid字段与该用户的Facebook ID相对应。
Let's say I have a User model, with a facebook_uid field corresponding to the user's facebook id.
我要允许用户取消其Facebook帐户的链接。这样做,我需要将此属性设置为nil。
I want to allow the user to unlink his facebook account. Do do so, I need to set this attribute to nil.
我目前看到这样做的两种方式
I currently see 2 ways of doing this
# app/controllers/users_controller.rb
def unlink_facebook_account
@user = User.find params[:id]
# Authorization checks go here
@user.facebook_uid = nil
@user.save
# Redirection go here
end
# config/routes.rb
ressources :users do
get 'unlink_fb', :on => :member, :as => unlink_fb
end
# in a view
= link_to "Unlink your facebook account", unlink_fb_path(@user)
第二种方式:为现有更新操作创建表单
Second way : create a form to the existing update action
# app/views/user/_unlink_fb_form.html.haml
= form_for @user, :method => "post" do |f|
= f.hidden_field :facebook_uid, :value => nil
= f.submit "Unlink Facebook account"
我不是超级粉丝无论哪种方式。
I'm not a big fan of either way.
-
在第一个中,我必须为更新控制器已经可以执行的操作添加新操作。
In the first one, I have to add a new action for something that the update controller already can do.
在第二个示例中,如果不自定义更新操作,则无法将facebook_uid设置为nil,并且如果不添加一些JavaScript,就不能拥有链接而不是按钮。 p>
In the second one, I cannot set the facebook_uid to nil without customizing the update action, and I cannot have a link instead of a button without adding some javascript.
不过,对于这种情况,您会推荐什么是最好,最优雅的解决方案?我是否错过了第三种选择?
Still, what would you recommend as the best and most elegant solution for this context? Did I miss a third alternative?
使用更新链接动作,以要更新的属性为参数;处理属性设置为0的情况
Use a link to the update action, with the attribute to update as parameters ; and handle the case when the attribute is set to 0
= link_to "Unlink your facebook account",
user_path(@user,
:user => { :facebook_uid => 0}),
:method => :put,
:confirm => "Are you sure?"
推荐答案
不确定您的路线是什么样,但是如果有一个更新操作,它应与link_to一起使用。如果您使用链接,请确保使用PUT或POST的方法(最好是PUT,因为它是更新):
Not sure what your routes look like but if you have an update action it should work with the link_to. If you go with the link make sure you use a method of PUT or POST (ideally PUT because it's an update):
link_to("Unlink your facebook account", user_path(@user, :facebook_uid => nil), :method => :put, :confirm => "Are you sure?")
这篇关于Rails-更新单个属性:使用自定义操作链接还是使用隐藏字段链接表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!