alex lug
alex lug

Reputation: 181

Rails missing required keys: [:id]

I've been trying to put up a basic website blog with users. And I had the idea of making the 'contact' page into a db, where you could manipulate the links that go inside. And edit them etc. But all on the same page avoiding creating edit.html.erb or show.html.erb. Just index and a _form, and I'm stomped. BTW this is the first website I try to develop in any language.

This is the index.html.erb that keeps failing on me.

<div class="indent50">
    <h3>For any questions contact me</h3>
    <% @contacts.each do |contact| %>
        <h5><%= link_to contact.name, "http://#{contact.clink}" %></h5>
        <h5><%= link_to "Edit",edit_contact_path(@contact) %></h5>
    <% end %>
</div>
<%= render "form" %>

raising No route matches {:action=>"edit", :controller=>"contacts", :id=>nil} missing required keys: [:id] here <h5><%= link_to "Edit",edit_contact_path(@contact) %></h5>

This is the contacts controller:

class ContactsController < ApplicationController
    before_action :find_contact, only: [:show, :edit, :update, :destroy]
    def index
        @contacts = Contact.all.order("created_at DESC")
    end
    def new
        @contact = Contact.new
    end

    def create
        @contact = Contact.new(post_params)
        if @contact.save
            flash[:notice] = "Contact created"
            redirect_to(:action=>'index', :contact_id => @contact.id)
        else
            @contacts = Contacts.order()
            render('new')
        end
    end

    def edit
    end

    private
    def find_contact
        @contact=Contact.find(params[:id])
    end
    def post_params
        params.require(:contact).permit(:name, :clink)
    end
end

Any suggestions? or even alternatives for what I had in mind. Thank you.

Upvotes: 1

Views: 2541

Answers (1)

Caillou
Caillou

Reputation: 1500

You need to replace @contact by contact in your link_to "Edit" line.

@contact doesn't exist, you need to use the loop variable that you created, named contact. That's why it says "missing required keys", because the @contact that you send has nil for value.

Upvotes: 4

Related Questions