Rails 4嵌套模型:如何使用json数据创建记录

时间:2015-12-02 05:33:34

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

我有如下嵌套模型:

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 vars接收并存储在DB中?

2 个答案:

答案 0 :(得分:4)

来自

"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)

答案 1 :(得分:-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

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