如何更新使用CollectionProxy构建的对象

时间:2014-05-12 09:03:10

标签: ruby-on-rails ruby-on-rails-4

我有两个表:客户端,检查

通过表单创建检查,该表单返回与给定客户端相关的CollectionProxy,如下所示:

inspections_controller.rb

def create    
  @inspcetion = @client.inspections.create(inspection_params)
  redirect_to client_inspections_path(@client) 
end

视图/检验/ _form.html

<%= form_for([@client, @client.inspections.build], :html => { :class => 'form' }) do |f| %>

现在我想知道如何更新现有检查。我相信对我的更新方法使用相同的表单,将始终创建一个新对象 - &gt; .build

是吗?

更新方法的url似乎调用了正确的检查(/ clients / cl_id / inspect / insp_id / edit),但是生成的表单显示为空(没有任何包含的信息用于创建检查)

<%= link_to 'Edit', edit_client_inspection_path(inspection.client, inspection) %>

我相信我必须在编辑视图中更改表单/ form_for,并且不应该呈现_form.html.erb,但是我完全不知道如何实现这一点。

这是来自inspections_controller.rb的简单更新方法

def update
  @inspection = @client.inspection.find(params[:id])
  respond_to do |format|
    if @inspection.update(inspection_params)
      format.html { redirect_to @inspection, notice: 'Inspection was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: 'edit' }
      format.json { render json: @client.inspection.errors, status: :unprocessable_entity }
    end
  end
end

那么,我如何更新属于CollectionProxy的对象?它可能很难:)

希望我的问题简明扼要,有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

而是在newedit行动中执行此操作

def new
  @client = # query for client
  @inspection = @client.inspections.new
end

def edit
  @client = # query to fetch client
  @inspection = @client.inspection
end

在你的部分

<%= form_for([@client, @inspection], :html => { :class => 'form' }) do |f| %>

通过这种方式,您可以使用相同的部分

来完成此操作

答案 1 :(得分:1)

.build将为该实例创建一个新的ActiveRecord对象。它与.new的作用相同,只是每次都必须填充数据。


从你所拥有的,我会说最大的问题是通过inspections通过每个客户。要解决这个问题,我会使用RSB的答案,并填充控制器中的@inspection var

在您的视图中使用.build方法永远不一个好主意,因为它不是模块化的