2016-06-10 87 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的内容,以确保它们对齐。