【问题标题】:Rails 4 nested model: How to create record using json dataRails 4 嵌套模型:如何使用 json 数据创建记录
【发布时间】:2015-12-02 05:33:33
【问题描述】:

我有如下嵌套模型:

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Project::Task < ActiveRecord::Base
  attr_accessible :task_id, :name
  belongs_to :Project
end

我有来自外部的 json 数据:

"project": {
      "name": "My Project Name",
      "tasks": [
        {"name": "Design prototype"},
        {"name": "Home page UI  prototype"},
        {"name": "Other Miscellaneous task"}
     ]
}

如何在 Rails 4 中创建控制器,接收上述 json 数据作为 POST 变量并将其存储在 DB 中?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4 nested-attributes


    【解决方案1】:

    来自

    "project": {
          "name": "My Project Name",
          "tasks": [
            {"name": "Design prototype"},
            {"name": "Home page UI  prototype"},
            {"name": "Other Miscellaneous task"}
         ]
    }
    

    "project": {
          "name": "My Project Name",
          "tasks_attributes": [
            {"name": "Design prototype"},
            {"name": "Home page UI  prototype"},
            {"name": "Other Miscellaneous task"}
         ]
    }
    

    在控制器中

    project_params = params.require(:project).permit(:name, tasks_attributes: [:name])
    Project.new(project_params)
    

    【讨论】:

      【解决方案2】:

      在项目新表单页面上执行以下操作:-

      <%= form_for @project do |f| %>
          <%= f.fields_for :tasks do |task| %>
              <%= task.text_field :name %>
          <% end %>
      <% end %>
      

      项目控制器:-

      def new
          @project = Project.new
          @project.tasks.build
      end
      
      def create
          @project = Project.new(project_params)
          if @project.save
              redirect_to success_path
          else
              render 'new'
          end
      end
      
      private
      def project_params
          params.require(:project).permit(:name, tasks_attributes: [:id, :name])
      end
      

      另外,从 Rails 4 中删除了 attr_accessible。在 Rails 4 中,我们需要允许控制器中的属性,例如项目控制器中的“project_params”方法。

      【讨论】:

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