Rails:验证后嵌套模型消失

时间:2016-01-26 18:05:43

标签: ruby-on-rails ruby-on-rails-4

我有一个模特:

include

我有一个带有https://github.com/nathanvda/cocoon的表单,但我有一个小问题 - 验证失败后,所有invoice_positions都会消失。

以下是我渲染位置的表单的一部分:

//MAIN VIEW
var addMoneyArray = [[Int]]()


class GonMainTableViewController: UITableViewController {

    //MARK: - VARIABLES
    var recivedData : Int?

    //MARK. - IB OUTLETS

    @IBOutlet var tableView1: UITableView!
    @IBAction func unwindViewController(segue: UIStoryboardSegue){
        if(segue.sourceViewController .isKindOfClass(GonDetailViewController))
        {
            let view2 : GonDetailViewController = segue.sourceViewController as! GonDetailViewController

          recivedData = view2.passTxtFieldValue


        }
    }




    enter code here

//VIEW2

class GonDetailViewController: UIViewController {

var passTxtFieldValue : Int?

 @IBAction func addBtn(sender: AnyObject) {
        var returnMoney = Int(addMoneyTxtField.text!)
        returnMoney =  passTxtFieldValue


        let alertController = UIAlertController(title: "Awesome!", message: "Succesfully saved your data!", preferredStyle: .Alert)
        let takePhotoAction = UIAlertAction(title: "OK", style: .Default) { (Alert) -> Void in
            self.performSegueWithIdentifier("returnToMain", sender: self)


        }
        alertController.addAction(takePhotoAction)
        presentViewController(alertController, animated: true, completion: nil)

    }

我在控制器中创建动作:

class Invoice < ActiveRecord::Base
  belongs_to :case
  has_many :invoice_positions

  accepts_nested_attributes_for :invoice_positions, allow_destroy: true

以下是来自控制台的参数:

<% f.fields_for :invoice_positions do |invoice_position| %>
            <%= render 'invoice_position_fields', f: invoice_position %>
        <% end %> 

这里是invoice_position_fields视图:

def create
    @case = Case.find(params[:case_id])
    @invoice = Invoice.new(invoice_params)
    @invoice.case = @case

    if @invoice.save
      flash[:success] = 'Faktura zapisana'
      redirect_to case_case_invoices_path(@case)
    else
      @invoice.invoice_positions.build(params[:invoice_positions_attributes])
      render 'new'
    end
  end

1 个答案:

答案 0 :(得分:1)

<%= f.fields_for :invoice_positions do |invoice_position| %>

而不是

<% f.fields_for :invoice_positions do |invoice_position| %>

2.5小时得到它....

-

Rich Peck编辑

您可以稍微清理一下create行动:

def create
   @case    = Case.find params[:case_id]
   @invoice = @case.invoices.new invoice_params