开发者

How to have form use a different controller

开发者 https://www.devze.com 2023-03-21 02:44 出处:网络
I have 3 Models: Location belongs_to :user has_many :products, :product_dates ProductDate belongs_to :user, :location

I have 3 Models:

Location
belongs_to :user
has_many :products, :product_dates

ProductDate 
belongs_to :user, :location
has_many :products

Product 
belongs_to :user, :location, :product_date

I have a nested form:

<%= form_for @location do |first| %>
<%= f.fields_for :prod开发者_StackOverflowuct_dates do |second| %>
<%= second.fields_for :products do |third| %>

I only have Two controllers but for my nested form am using ProductsController:

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

I want it to use my ProductsController because i need this Nested Form to redirect to Products/INDEX on save and not Locations/Show because my LocationsController is for creating Locations only and not many Products. How do i accomplish this?

Note: I have little Ruby and Rails experience.


1) you can use nested routes instead:

resources :locations do
  resources :product_dates
  resources :products
end

2) model Location should has the accepts_nested_attributes_for

class Location < AR:BAse
  accepts_nested_attributes_for :product_dates, :products
end

3) controller should not build children object, because you can only initialize and save parent object, children will be saved automatically


If you want to have your form_for use a different controller you do:

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

If it is nested like my situation then you my also have your children fields do the same.

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

and

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

Then i redirect back to my 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
0

精彩评论

暂无评论...
验证码 换一张
取 消