我还是有点新手,但是我看到了奇怪的行为,并想知道这是不是常规或者我做错了什么。
我有以下嵌套资源:
resources :accounts do
resources :users
end
他们正在生成标准的restful url(host.com/accounts/my-account-name/users/33/edit),除非用户的UPDATE失败(例如由于验证)。然后它生成一个url,如host.com/accounts/22/users/22,或者基本上是host.com/accounts/:user_id/users/:user_id
这里发生了什么?该应用程序仍将更新用户,但我不明白为什么这样做。任何帮助或理解表示赞赏。
用户控制器如下:
def update
respond_to do |format|
if @user.update(user_params)
format.html{
redirect_to account_users_path(@user.account),
notice: 'User was successfully updated.'
}
else
format.html { render :edit }
end
end
end
这是我的表格:
.card
.header Edit User
.content
= form_for(@user, url: account_user_path(@user), html: {class: 'form-horizontal'}) do |f|
.content
- if @user.errors.any?
.alert.alert-danger
h4 = "#{pluralize(@user.errors.count, 'error')} prohibited the user from being saved."
== @user.errors.full_messages.map{|msg| content_tag(:li, msg)}.join
.form-group
= f.label :name, class: 'control-label col-lg-2'
.col-lg-10
= f.text_field :name, {placeholder: 'Name', autofocus: true,class: 'form-control'}
.form-group
= f.label :email, class: 'control-label col-lg-2'
.col-lg-10
= f.email_field :email, {placeholder: 'Email', class: 'form-control'}
.form-group
= label_tag "user[role]", "Role", class: 'control-label col-lg-2'
.col-lg-10
= select_tag "user[role]", options_for_select(@choices,@user.roles.first.name), class:'form-control'
.footer style ="height: 55px;"
span.pull-left
= link_to 'Cancel', account_users_path, class: 'btn btn-primary btn-warning'
span.pull-right
=f.submit "Save", class: 'btn btn-primary'
.footer style ="height: 55px;"
- if current_user.has_role?(:owner, current_account)
span.pull-right
= link_to 'Delete', account_user_path(@user), {method: :delete, data: {confirm: 'Are you sure?'},
class: 'btn btn-danger'} unless @user.id == current_user.id
我不知道是什么问题,据我所知,你的嵌套路线工作正常: - 让我解释一下
当你运行rake routes | grep users
get 'accounts/my-account-name/users/:user_id/edit',to: 'users#edit'
put 'accounts/:account_id/users/:user_id', to: 'users#update'
patch 'accounts/:account_id/users/:user_id', to: 'users#update'
所以这里为你需要通过url和控制器传递account_id
所需的每一个动作,你需要在任何动作之前设置@account
。你可以在users controller
这样做
before_action: get_account
private
def get_account
@account = Account.find(params[:id])
end
并为您的edit_form
传递第一个参数作为account
对象和user
对象,并指定更新操作的方法类型
= form_for(@user, url: account_user_path(@account,@user), html: {class: 'form-horizontal', method: :patch}) do |f|