你能使一个表单对象工作的新和编辑操作,如果表单本身从来没有被持久化?



我正试图使newUsereditUser行动的形式对象工作。表单对象通过它的save方法创建或更新User,但表单对象本身从未持续存在,所以Rails总是尝试POST,即使我在simple_form_forurl中指定不同的路由。

是否有办法使它对两个动作都起作用?

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_withlink_to多态路由助手调用to_model.model_name.route_keysingular_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

相关内容

  • 没有找到相关文章

最新更新