Search code examples
rubyruby-on-rails-4crudnested-formslink-to

Rails 4 nested forms link_to edit not working in loop


I have a nested routes/models/forms in rails. On my index page I am listing the todo_lists with the todo_items underneath. I want to be able to click on my todo list title and then it takes me to the edit page. I research polymorphic routes and nested routes.

UPDATE

This was my fix to stop it from creating the dummy todo list.

<%  @current_todo_lists.each do |list| %>
    <% if list.id %>
        <div class="panel">
            <p><strong><%= link_to list.title ,edit_todo_list_path(list)%></strong></p>
            <% list.todo_items.each do |todo_item| %>
                <p><%= todo_item.description %></p>
            <% end %>
        </div>
    <% end %>
<% end %>

github link

Link_to rails nested form edit

polymorphic_path not generating correct path I have done a lot quite a bit of research looking to cocoon, rails guides on polymorphic routes and several other stackoverflow links.

I have not been successful in making any of these work.

Here is the index page where all my todo_lists with todo_items are listed. It goes through a loop to list each todo list with the corresponding items created with it

Update:

I already tried <%= link_to list.title, edit_todo_list_path(list) %>and <%= link_to list.title, edit_todo_list_path(@list) %>. The error message I get is :

ActionController::UrlGenerationError at /todo_lists No route matches {:action=>"edit", :controller=>"todo_lists", :id=>nil} missing required keys: [:id] This same configuration with @todo_list gives the same error. Basically it can't find the Todo List with an id.

In the console does give me a result. So I am missing something.

>> t = TodoList.find(1)
=> #<TodoList id: 1, title: "First todo List with a modal", created_at: "2014-09-09 23:02:27", updated_at: "2014-09-09 23:02:27", user_id: 1>
>>

Update 2: This is where the error is happening in my todo list controller. It can't find without id.

def set_todo_list
@todo_list = TodoList.find(params[:id])
end


<% @todo_lists.each do |list| %> 
    <p><strong><%= link_to list.title, edit_polymorphic_path(@todo_list) %></strong></p>
    <% list.todo_items.each do |todo_item| %>
        <p><%= todo_item.description %></p>
    <% end %>
<% end %>

So far <p><strong><%= link_to list.title, edit_polymorphic_path(@todo_list) % parameters have been @todo_list(s), @ todo_lists(s), todo_items and so on.

Models:

class TodoList < ActiveRecord::Base
    has_many :todo_items, dependent: :destroy
    accepts_nested_attributes_for :todo_items, allow_destroy: true
    validates_presence_of :title
end

class TodoItem < ActiveRecord::Base
    belongs_to :todo_list
end

Controllers:

Class TodoListsController < ApplicationController
  before_filter :authenticate_user!
  before_filter except: [:index]
  before_action :set_todo_list, only: [:show, :edit, :update, :destroy]

  # GET /todo_lists
  # GET /todo_lists.json
  def index
    #@todo_lists = TodoList.all
    #find current user todo lists/items
    @todo_lists = current_user.todo_lists
    @todo_items = current_user.todo_items
    #create a new user todo list
    @todo_list = current_user.todo_lists.new
    # builder for todo list _form
    3.times{ @todo_list.todo_items.build }
  end

  # GET /todo_lists/1
  # GET /todo_lists/1.json
  def show
  end

  # # GET /todo_lists/new
  def new
    @todo_list = current_user.todo_lists.new
    3.times{ @todo_list.todo_items.build }
  end

  # GET /todo_lists/1/edit
  def edit
    #@todo_list = TodoList.find(todo_list_params)
    @todo_list = TodoList.find(params[:id])
  end

  # POST /todo_lists
  # POST /todo_lists.json
  def create
    #@todo_list = TodoList.new(todo_list_params)
    @todo_list = current_user.todo_lists.new(todo_list_params)
    respond_to do |format|
      if @todo_list.save
        format.html { redirect_to @todo_list, notice: 'Todo list was successfully created.' }
        format.json { render :show, status: :created, location: @todo_list }
      else
        format.html { render :new }
        format.json { render json: @todo_list.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /todo_lists/1
  # PATCH/PUT /todo_lists/1.json
  def update
    @todo_list = TodoList.find(params[:id])
    respond_to do |format|
      if @todo_list.update(todo_list_params)
        format.html { redirect_to @todo_list, notice: 'Todo list was successfully updated.' }
        format.json { render :show, status: :ok, location: @todo_list }
      else
        format.html { render :edit }
        format.json { render json: @todo_list.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /todo_lists/1
  # DELETE /todo_lists/1.json
  def destroy
    #@todo_list.TodoList.find(params[:id])
    @todo_list.destroy
    respond_to do |format|
      format.html { redirect_to todo_lists_url, notice: 'Todo list was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def owns_todolist
      if current_user != TodoList.find(params[:id]).user
        redirect_to todo_lists_path, error: "You can't do that!"
      end
    end
    # Use callbacks to share common setup or constraints between actions.
    def set_todo_list
      @todo_list = TodoList.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def todo_list_params
      params.require(:todo_list).permit(:title, todo_items_attributes: [:description, :_destroy])
    end
end



class TodoItemsController < ApplicationController
  before_action :set_todo_item, only: [:show, :edit, :update, :destroy]
  before_action :set_todo_list

  # GET /todo_items
  # GET /todo_items.json
  def index
    @todo_items = TodoItem.all
  end

  # GET /todo_items/1
  # GET /todo_items/1.json
  def show
    @todo_item = TodoItem.find(params[:id])
  end

  # GET /todo_items/new
  def new
    @todo_item = @todo_list.todo_items.build
  end

  # GET /todo_items/1/edit
  def edit
    @todo_item = TodoItem.find(params[:id])
  end

  # POST /todo_items
  # POST /todo_items.json
  def create
    @todo_item = @todo_list.todo_items.build(todo_item_params)

    respond_to do |format|
      if @todo_item.save
        format.html { redirect_to [@todo_list,@todo_item], notice: 'Todo item was successfully created.' }
        format.json { render :show, status: :created, location: @todo_item }
      else
        format.html { render :new }
        format.json { render json: @todo_item.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /todo_items/1
  # PATCH/PUT /todo_items/1.json
  def update
    @todo_item = TodoItem.find(params[:id])
    respond_to do |format|
      if @todo_item.update(todo_item_params)
        format.html { redirect_to @todo_item, notice: 'Todo item was successfully updated.' }
        format.json { render :show, status: :ok, location: @todo_item }
      else
        format.html { render :edit }
        format.json { render json: @todo_item.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /todo_items/1
  # DELETE /todo_items/1.json
  def destroy
    @todo_item = TodoItem.find(params[:id])
    @todo_item.destroy
    respond_to do |format|
      format.html { redirect_to todo_list_todo_items_url, notice: 'Todo item was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_todo_item
      @todo_item = TodoItem.find(params[:id])
    end

    def set_todo_list
      @todo_list = TodoList.find(params[:todo_list_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def todo_item_params
      params.require(:todo_item).permit(:description, :text, :todo_list_id)
    end
end

and finally the form. Right now it allows for adding a todo_list and a few todo_items just as practice. I plan on using some Ajax to allow for dynamic creation later on. And having a different form for editing.

<%= form_for(@todo_list) do |f| %>
  <% if @todo_list.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@todo_list.errors.count, "error") %> prohibited this todo_list from being saved:</h2>

      <ul>
      <% @todo_list.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.fields_for :todo_items do |builder| %>
      <%= builder.label :description, "Items" %>
      <%= builder.text_field :description %>
      <%= builder.check_box '_destroy' %>
    <% end %>

  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Solution

  • I think the issue's actually a little trickier, because edit_todo_list_path(list) seems to throw the same error.

    What's going on is that the @todo_lists variable (first an array of persisted lists) is altered when you run @todo_list = current_user.todo_lists.new. That command actually adds a new (unpersisted) list to the end of the @todo_lists array (seems like buggy behavior to me, but it's happened to me before), so that when your view is looping through them, the last one has no id, and a path cannot be created for it.

    The solution is (I think) to make that variable after you've used the @todo_lists variable.

    Take @todo_list out of the controller, and where you use it in the view, instead do current_user.todo_lists.build. That should instantiate a new list without changing the @todo_lists variable.