首页 文章

RoR - 新的更新操作

提问于
浏览
0

我有两个型号

Client.rb
  has_many :addresses
  accepts_nested_atributes_for :addresses


Address.rb
  has_many :addresses

我在 ClientsController 上创建了一个新动作 update_establishments ,以便向客户端添加新的机构 .

ClientsController.rb

   #the corresponding view of this action will render the locations_form
   def add_establishments
    @client = Client.find(params[:id])
    @client.addresses.build
   end

   def update_establishments
    create_zip
    respond_to do |format|
      if @client.update(client_params)
        set_zip
        format.html { redirect_to @client, notice:'Establishment added.'}
        format.json {head :no_content}
      else
        format.html { render action: 'edit'}
        format.json { render json: @client.error, status: :unprocessable_entity }
      end
    end
   end


locations_form

   %= form_for @client, :url=>{:action=>'update_establishments'}, html:{ :method =>"patch"}  do |form| %>

我有两个问题:

1 - 表单呈现时,表单为地址显示两个单独的字段,一个包含现有地址的值,另一个包含新的 . 如何才能不显示现有地址?

2 - 它在 update_establishments 动作上给出了明显的错误,因为 @client 为零 . 有没有办法将客户端本身从表单发送到操作,还是我必须添加带有值的隐藏字段?

1 回答

  • 1

    问题1,当你致电 @client.addresses.build 时,它正在为客户 Build 第三个地址 . 我的猜测是你在表单上显示所有三个地址 .

    问题2,您将要发送带有请求的客户端ID,并使用它来查找客户端 .

    以下应解决这两个问题 .

    尽可能 - 并且几乎总是可能的 - 尝试坚持standard Rails controller actions . 非标准控制器操作(如 add_establismentsupdate_establishments )通常表示存在更多"Rails"方式来为控制器建模 .

    在这种情况下,我会质疑为什么 ClientsContoller 正在处理机构 . 如果你添加 EstablishmentsController ,我的猜测是事情才会开始起作用 . 以下是如何做到这一点:

    在config / routes.rb中,创建具有嵌套企业资源的客户端资源 .

    resources :clients do
      resources :establishments
    end
    

    这将为您提供一些nested routes,它们都将以/ clients /:client_id / establishment开头 .

    创建 EstablishmentsController 并将 add_establishmentsupdate_establishments 移动到它 . 将 add_establishments 重命名为 new 并将 update_establishments 重命名为 update . 同时将相应的视图移动到/ views / establishmentments /并重命名它们以匹配其新的操作名称 .

    如果没有令人信服的理由在 new 动作中找到客户端,您可以构建一个新的机构以传递给视图 . 无论哪种方式,您的表单都将与此新 Build 相关联,而不是与现有客户相关联 . (问题1)

    update 中,您将使用 :client_id param来查找客户端 . (问题2) update 将需要一些按摩,但我真的要一次更新多个机构或只是一个机构来说明它会是什么样子 . (您不会更新 @client 本身,而是客户的场所 . )

相关问题