2016-06-10 118 views
0

我試圖做一個應用程序,它允許人們向一個模型提交信息,同時也從另一個模型填充一些關於它的數據。目前形式的作品,但對於嵌套表格中的數據不保存Rails 4嵌套表單數據沒有被保存,有很多通過關聯

這裏是我的控制器

class Requests::AgesController < ApplicationController 
    def new 
     @age = Age.new 
     @industries = Industry.all.map{ |i| [i.name, i.id ]} 
     @age.ages_industries.build 
    end 

    def create 
    @age = Age.new(age_params) 

    if @age.save 
     flash[:success] = "Age #{@age.name} has been created!" 
     redirect_to admin_ages_path 
    else 
     flash.now[:error] = "Sorry! We were unable to create that age." 
     render "new" 
    end 
    end 

    private 

    def age_params 
    params.require(:age)\ 
      .permit(:name, 
        :about_title, 
        :about_body, 
        :url, 
        :email, 
        :phone, 
        :street, 
        :city, 
        :state, 
        :zip, 
        :country, 
        :is_published, 
        age_industries_attributes: [:age_id, :industry_id]) 
    end   
end 

年齡模型

has_many :ages_industries, 
    dependent: :delete_all 
    accepts_nested_attributes_for :ages_industries 


has_many :industries, 
    :through => :ages_industries, 
    :uniq => true 

ages_industries模型

class AgesIndustry < ActiveRecord::Base 
    belongs_to :age, touch: true 
    belongs_to :industry 
    accepts_nested_attributes_for :industry 
    self.primary_key = :id 
end 
的相關位

相關位行業模型

has_many :ages_industries 
has_many :ages, 
    :through => :ages_industries, 
    :uniq => true 

形式

section#main 
    .wrapper 
     h1 Add an Age 
     = simple_form_for [:requests, @age] do |form| 
      .formElem.m20t.m20b 
       = form.error_notification 
      .formElem.m20b 
       = form.input :name 
      .formElem.m20b 
       = form.simple_fields_for :ages_industries do |builder| 
        = builder.input :industry_id, collection: @industries, :value => params[:id] 
      .fix 
      .formElem.m20b 
       = form.input :about_title 
      .formElem.m20b 
       = form.input :about_body 
      .formElem.m20b 
       = form.input :url 
      .formElem.m20b 
       = form.input :email 
      .formElem.m20b 
       = form.input :phone 
      .formElem.m20b 
       = form.input :street 
      .formElem.m20b 
       = form.input :city 
      .formElem.m20b 
       = form.input :state 
      .formElem.m20b 
       = form.input :zip 
      .formElem.m20b.m20t 
       = form.input :country, collection: Carmen::country_names 
      .fix 
      .formElem.m20b 
       = form.input :is_published 
      .formElem.m20b.m20t 
       = form.button :submit, class: "formBtn" 
       | or 
       = link_to "cancel", admin_ages_path 

如果有人可以點我在正確的方向,這將不勝感激。

+0

你可以發佈表單嗎? – steel

+0

這是一個錯誤? 'params.require(:年齡)\' – steel

回答

1

至少,當你允許嵌套參數時,你錯過了複數形式。即年齡而不是年齡。

params.require(:age).permit(ages_industries_attributes: [...]) 

如果不解決的話,我會把你的控制器prybyebug創建行動,並檢查出的paramsage_params的內容,以確保它們對齊。

相關問題