Rails 3 - 如何编辑单个嵌套多态资源?

时间:2012-01-30 01:06:58

标签: ruby-on-rails ruby-on-rails-3 nested edit polymorphism

在我的Rails 3.0应用程序中,我有一个客户端模型和一个多态地址模型。根据下面的代码,客户端可以有许多地址。我希望我的表单一次更新一个客户端地址。如果我允许同时编辑所有客户端的地址,我似乎只能显示[addresses_attributes]。有办法解决这个问题吗?

class Client < ActiveRecord::Base
 has_many :addresses, :as => :addressable, :dependent => :destroy
 accepts_nested_attributes_for :addresses

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true

客户端控制器

  def edit
    @client = Client.find(params[:id])
    @addresses = @client.addresses
    if params[:address]
      @address = @client.addresses.find(params[:address])
    else
      @addresses ? @address = @addresses.first : @address = []
    end
  end

   def update
     @client = Client.find(params[:id])
     @client.update_attributes(params[:client])
     redirect_to client_path(@client)
   end

查看

<%= form_for @client do |f| %>
  <%= render :partial => 'form', :locals => {:f => f} %>

  <%= f.fields_for @address  do |addresses_attributes| %>
     <%= render :partial => 'addresses/fields', :locals => {:f => addresses_attributes} %>             
  <% end %>

  <%= f.submit %>
<% end %>

1 个答案:

答案 0 :(得分:0)

编辑:

抱歉,我重读了这篇文章并意识到有更好的选择。您应该向Address模型添加范围,或者您应该使用条件在Client中创建单独的关联。

http://railscasts.com/episodes/108-named-scope 或者看这里的条件: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

DETAIL:

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
  named_scope :type_one, :conditions => { :address_type => 'one' }
  named_scope :type_two, :conditions => { :address_type => 'two' }

<%= f.fields_for @address.type_one  do |addresses_attributes| %>
  <%= render :partial => 'addresses/fields', :locals => {:f => addresses_attributes} %>             
<% end %>