如何让表单使用不同的控制器

时间:2011-07-15 20:06:54

标签: ruby-on-rails ruby-on-rails-3 nested-forms

我有3个型号:

Location
belongs_to :user
has_many :products, :product_dates

ProductDate 
belongs_to :user, :location
has_many :products

Product 
belongs_to :user, :location, :product_date

我有一个嵌套的表单:

<%= form_for @location do |first| %>
<%= f.fields_for :product_dates do |second| %>
<%= second.fields_for :products do |third| %>

我只有两个控制器,但我的嵌套表单是使用ProductsController:

def new
  @location = Location.new
  3.times do
    product_date = @location.product_dates.build
    4.times { product_date.products.build }
  end
end

我希望它使用我的ProductsController,因为我需要这个嵌套表单在保存时重定向到Products / INDEX而不是Locations / Show,因为我的LocationsController仅用于创建Locations而不是很多Products。我该如何做到这一点?

注意:我没有Ruby和Rails的经验。

2 个答案:

答案 0 :(得分:1)

1)您可以改为使用嵌套路线:

resources :locations do
  resources :product_dates
  resources :products
end

2)model Location应该有accepts_nested_attributes_for

class Location < AR:BAse
  accepts_nested_attributes_for :product_dates, :products
end
3)控制器不应该构建子对象,因为你只能初始化并保存父对象,孩子会自动保存

答案 1 :(得分:1)

如果您想让form_for使用不同的控制器:

<%= form_for @location, :url => products_path do |f| %>

如果它像我的情况一样嵌套,那么你我的孩子们也会做同样的事情。

<%= f.fields_for :product_dates, :url => products_path do |date| %>

<%= date.fields_for :products, :url => products_path do |product| %>

然后我重定向回我的Products / INDEX:

def create
        @location = Location.new(params[:location])
        if @location.save
            redirect_to :action => 'index', :notice => "Successfully created products."
        else
            render :action => 'new'
        end
    end