ruby on rails - How to create the child for existing object with self-referential associations? -


i have model self-referential associations:

class task < activerecord::base   has_many    :subtasks, class_name: 'task', foreign_key: "parent_id"   belongs_to  :parent, class_name: 'task'   accepts_nested_attributes_for :subtasks, allow_destroy: true   belongs_to  :user   belongs_to  :project end 

the meaning is:

  • i create tasks
  • to of tasks wanna add subtasks
  • when i'm going task_path - /tasks/:id, action 'tasks#show' - see attributes of task, below want have opportunity add subtasks.

and questions in addition:

  1. is way use 1 model tasks , subtasks?
  2. do need create second controller?

thank , sorry english.

upd1: taskscontroller

class taskscontroller < applicationcontroller    before_action :find_task, only: [:show, :edit, :update, :destroy]    def index     @tasks = task.where("parent_id ?", nil)   end    def show   end    def new     @task = task.new     @task.subtasks.build   end    def edit   end    def create     @task = task.create(task_params)     if @task.errors.empty?       redirect_to @task     else       render  'new'     end   end    def update     @task.update_attributes(task_params)     if @task.errors.empty?       redirect_to @task     else       render  'edit'     end   end    def destroy     @task.destroy     redirect_to tasks_path   end    private    def task_params     params.require(:task).permit(:title, :description, :priority, :status, :scheduled, :deadline, subtasks_attributes: [:title])   end   def find_task     @task = task.find(params[:id])   end end 

show.html.erb tasks/:id (just rough draft)

<%= @task.deadline %> <%= @task.title %> <%= @task.description %> <% @task.subtasks.each |s| %>   <br><%= s.title %>   <%= link_to 'delete', [s], method: :delete, data: { confirm: 'are sure?' } %> <% end %>  <%= simple_form_for @task |t| %> <%= t.simple_fields_for :subtasks |f| %>   <%= f.error_notification %>   <div class="form-inputs">     <%= f.input :title %>    </div>    <div class="form-actions">     <%= f.button  :submit %>   </div> <% end %> <% end %> 

you can use accept_nested_attributes_for subtasks

http://api.rubyonrails.org/classes/activerecord/nestedattributes/classmethods.html

also consider using simple_form passing nested model attributes

https://github.com/plataformatec/simple_form/wiki/nested-models

with approach, no need create separate controller subtasks

i think use subtasks 1 parent task


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -