Rails 4 nested model: How to create record using json data

I have nested model like following:

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

I have json data coming from outside:

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

How can I create controller in Rails 4 which receives above json data as POST vars and store it in DB?

Answers


from

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

to

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

in controller

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

On project new form page do this:-

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

Project controller:-

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

Also, attr_accessible is removed from Rails 4. In Rails 4 We need to permit attributes in controller like "project_params" method in project cntroller.


Need Your Help

iOS: Uploading image to server, cannot be opened

ios objective-c http upload http-post

I am using the following code to upload an image to my servlet.

How to add a notification with button?

android android-notifications android-remoteview

I am a begginer, In my app I have a notification for image upload progress, I want to add a button with that notification, and I want to cancel the upload service when user clicks on the button. I ...