嵌套表单Rails 4.0强参数

时间:2014-07-17 06:20:41

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

整晚都在尝试这个,但我无法上传照片。 2个表工作得很好,但在保存照片的多态表上没有骰子。任何新鲜的眼睛都会有很大的帮助。

def restaurant_params
    params.require(:restaurant).permit(:res_name, :res_description, restaurant_branches_attributes: [ :id, :address_line1, :address_line2, :address_line3, :address_line4, :address_line5, :address_line6, :number_phone, :number_fax, :email, :_destroy ], pictures_attributes: [ :id, :name, :image] )
end

class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
mount_uploader :image, ImageUploader

class Restaurant < ActiveRecord::Base
has_many :restaurant_branches
accepts_nested_attributes_for :restaurant_branches, allow_destroy: true

class RestaurantBranch < ActiveRecord::Base
belongs_to :restaurants 
has_many :pictures, as: :imageable
accepts_nested_attributes_for :pictures, allow_destroy: true
before_save :set_address

def set_contact_info
    contact_info = "Phone: #{self[:number_phone]} Fax: #{self[:number_fax]} Email: #{self[:email]}"
end

def set_address
    address = self.address_line2.nil? ? partial_address.titleize : complete_address.titleize
end

private 

def complete_address
    address = "#{self[:address_line1]} #{self[:address_line2]} #{self[:address_line3]} #{self[:address_line4]} #{self[:address_line5]} #{self[:address_line6]}"
end

def partial_address
    address = "#{self[:address_line1]} #{self[:address_line3]} #{self[:address_line4]} #{self[:address_line5]} #{self[:address_line6]}"
end

1 个答案:

答案 0 :(得分:1)

多级协会

关联的多态性不应该是是一个问题,因为Rails通常会将数据发送到association - 在这种情况下pictures

我认为您的问题更多地与您拥有的多级关联有关,特别是您需要按以下方式传递属性[form submit] > RestaurantBranch > Pictures

-

我们之前已经完成了这项工作,以及您的工作方式:

#app/controllers/restaurants_controller.rb
Class RestaurantsController < ApplicationController
   def new
       @restaurant = Resaurant.new
       @restaurant.restaurant_branches.build.pictures.build #-> notice multi-level nesting
   end

   def create
       @restaurant = Restaurant.new(restaurant_params)
       @restaurant.save
   end

   private

   def restaurant_params
        params.require(:restaurant).permit(:res_name, :res_description, restaurant_branches_attributes: [ :id, :address_line1, :address_line2, :address_line3, :address_line4, :address_line5, :address_line6, :number_phone, :number_fax, :email, :_destroy,  pictures_attributes: [ :id, :name, :image]])
   end
end

#app/views/restaurants/new.html.erb
<%= form_for @restaurant do |f| %>
     <%= f.fields_for :restaurant_branches do |rb| %>
         <%= rb.fields_for :pictures do |p| %>
             <%= p.file_field :image %>
         <% end %>
     <% end %>
<% end %>