Rails 4 - belongs_to嵌套对象字段未保存

时间:2016-07-04 09:01:28

标签: ruby-on-rails ruby-on-rails-4 nested-attributes strong-parameters belongs-to

注意:我读过几篇与此类似的帖子。但是没有解决方案对我有用 我有两个对象Appeal和Appealer,有一对多的关系。保存Appeal对象时,将保存所有字段,并保存appealer id(如FK)。但是在Appealer表中保存了一条新记录,除了id之外没有任何数据。

MODEL

class Appeal < ActiveRecord::Base
    belongs_to :appealer, :autosave => true
    accepts_nested_attributes_for :appealer
end

class Appealer < ActiveRecord::Base
    has_many :appeals, :autosave => true
end

AppealsController

class AppealsController < ApplicationController
    def index
        respond_with Appeal.all
    end

    def create
        appealer = Appealer.create(appealer_params)
        @appeal = Appeal.create(appeal_params)
        @appeal.appealer = appealer


        if @appeal.save
          respond_with @appeal
        else
          respond_with {:error}
        end
    end

    def show
        respond_with Appeal.find(params[:id])
    end

    private
    def appeal_params
        params.require(:appeal).permit(:subject, :status, :submit_means, :card_type, :submit_date, :relationship, :report_date, :explanation, :email_approval)
    end
    def appealer_params
        params.require(:appeal).permit(appealer: [:appealer_id, :first_name, :last_name])
    end
end

修改 这是我使用的json

{
        "id": 21,
        "subject": "axxxscaaaa",
        "status": "happy",
        "submit_means": "DOAR",
        "card_type": "sdsd",
        "submit_date": 1466629200000,
        "relationship": null,
        "report_date": 1466542800000,
        "explanation": "sdsd",
        "email_approval": null,
        "appealer": {"first_name":"aaaaaaa", "last_name":"fffff"},
        "selfRequest": false,
        "created_at": 1465851600000,
        "updated_at": 1465333200000
    }

我不明白为什么上诉人的字段没有保存

2 个答案:

答案 0 :(得分:2)

  • 当您显示JSON对象时,您没有在视图表单上使用rails fields_for或其他内容。因此,您的模型中不需要这个( accepts_nested_attributes_for:appealer )行。模型应该是这样的:

    id
  • 接下来,在你当前的逻辑中,对于你的appealer_params,用这个改变appealer_params方法:

    B
  • 为您的方案创建操作逻辑:

      class Appeal < ActiveRecord::Base
        belongs_to :appealer, :autosave => true
      end
    

答案 1 :(得分:0)

试试这个

def appeal_params
   params.require(:appeal).permit(:subject, :status, :submit_means, :card_type, :submit_date, :relationship, :report_date, :explanation, :email_approval, appealers_attributes: [:id, :first_name, :last_name] )
end

并删除此行appealer = Appealer.create(appealer_params)