【问题标题】:foreignkey not saved in nested model rails外键未保存在嵌套模型导轨中
【发布时间】:2013-12-06 13:31:55
【问题描述】:

我的应用程序中有两个表

rfp.rb

            has_many :rfp_hors
            attr_accessible :rfp_hors_attributes
            accepts_nested_attributes_for :rfp_hors, :allow_destroy => true

rfp_hor.rb

      attr_accessible   :numberofmenu_est_hours,
     :numberofmenu_act_hours,
     :browser_est_hours,
     :browser_act_hours,
     :numberofpage_est_hours,
     :numberofpage_act_hours,
     :rfp_id

belongs_to :rfp

当我提交 rfp_hors 时,参数在控制台中显示如下

              Parameters: {"rfp_hor"=>{"ecommerce_est_hours"=>"7", "rfp_id"=>"13", "designcomplexity_est_hours"=>"3", "browser_est_hours"=>"4", "framworks_est_hours"=>"5", "cms_est_hours"=>"6"}, "utf8"=>"✓", "commit"=>"Create Rfp hor", "authenticity_token"=>"XXgQlufpBP2lvcde/EiFIx93aM5Ov47MNFqsCkLun2Y="}

和控制器 rfps.rb

    def show
        @rfp = Rfp.find(params[:id])
    @rfp_hor = RfpHor.new
    end

rfp_hors.rb

     def create
              @rfp_hor = RfpHor.create(params[:rfp_hor])

respond_to do |format|
  if @rfp_hor.save
   format.html { redirect_to rfp_url(@rfp_hor.rfp_id), :notice => 'rfp hour was successfully created.' }
    format.json { render :json => @rfp_hor, :status => :created, :location => @rfp_hor }
  else
    format.html { render :action => "new" }
    format.json { render :json => @rfp_hor.errors, :status => :unprocessable_entity }
  end
end

结束

在 rfp_hors 中的数据库 aceept rfp_id 中的所有内容都保存得很好 任何帮助都将非常感谢提前

【问题讨论】:

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


    【解决方案1】:

    您的问题是因为您将变量 @rfp_hor 初始化为 rfps 控制器中的新独立对象,您何时只初始化变量 @rfp,您可以尝试这种方式:

    def edit 
        @rfp = Rfp.find(params[:id])
    end
    

    在同一控制器的更新操作上,您无需更改任何内容,并且可以将此代码放入您的表单中:

    <%= form_for @rfp do |f| %>
       <%= f.fields_for : rfp_hors do |item| %>
          <%= item.field_one :field %>
          <%= item.field_two :field %>
       <% end %>
    <% end %>
    

    通过这种方式,您可以在更新操作中以嵌套形式在同一控制器中接收参数,并且可以显示此模式的参数:

    Parameters: {"rfp"=>{"rfp_hors_attributes"=>{"ecommerce_est_hours"=>"7", "rfp_id"=>"13", "designcomplexity_est_hours"=>"3", "browser_est_hours"=>"4", "framworks_est_hours"=>"5", "cms_est_hours"=>"6"}}, "utf8"=>"✓", "commit"=>"Create Rfp hor", "authenticity_token"=>"XXgQlufpBP2lvcde/EiFIx93aM5Ov47MNFqsCkLun2Y="}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多