我正试图使new
User
和edit
User
行动的形式对象工作。表单对象通过它的save
方法创建或更新User
,但表单对象本身从未持续存在,所以Rails总是尝试POST,即使我在simple_form_for
url中指定不同的路由。
是否有办法使它对两个动作都起作用?
UsersController.rb:
class Admin::UsersController < AdminController
def new
@user_form = UserForm.new(account_id: current_account.id)
end
def create
@user_form = UserForm.new(user_form_params)
if @user = @user_form.save
flash[:success] = "User created"
redirect_to admin_user_path(@user)
else
render "new"
end
end
def edit
@user_form = UserForm.new(existing_user: @user, account_id: current_account.id)
end
def update
if @user.update(user_form_params)
flash[:success] = "User saved"
redirect_to admin_user_path(@user)
else
render "edit"
end
end
end
UserForm.rb
class UserForm
include ActiveModel::Model
include ActiveModel::Validations::Callbacks
attr_accessor :fname, :lname, :email
def initialize(params = {})
super(params)
@account = Account.find(account_id)
@user = existing_user || user
end
def user
@user ||= User.new do |user|
user.fname = fname
user.lname = lname
user.email = email
end
end
def save
@user.save
@user
end
end
_form.html.erb
<%= simple_form_for @user_form, url: (@user.present? ? admin_user_path(@user) : admin_users_path) do |f| %>
<%= f.input :fname %>
<%= f.input :lname %>
<%= f.input :email %>
<%= f.submit %>
end
新的/create流程工作得很好,但是编辑现有的User
返回
No route matches [POST] "/admin/users/69"
class UserForm
# ...
def to_model
@user
end
end
<%= simple_form_for @user_form, url: [:admin, @user_form] do |f| %>
<%= f.input :fname %>
<%= f.input :lname %>
<%= f.input :email %>
<%= f.submit %>
end
当你传递一个记录到form_for
(SimpleForm包装),form_with
或link_to
多态路由助手调用to_model.model_name.route_key
或singular_route_key
取决于是否模型是persisted?
。传递[:admin, @user_form]
将导致多态路由助手使用admin_users_path
而不仅仅是users_path
。
在正常模型下,to_model
只返回self。
https://api.rubyonrails.org/v6.1.4/classes/ActionDispatch/Routing/PolymorphicRoutes.html