0

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?

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.