Hassan Yousuf
Hassan Yousuf

Reputation: 731

RoR - UrlGenerationError, no routes matches, missing required key [:id]

I am trying to create a posts pages. Where users can see all the public posts. I can successfully create posts but I can't see them.

ActionController::UrlGenerationError in Ribbits#index Showing C:/Sites/myBlog/app/views/ribbits/index.html.erb where line #8 raised:

No route matches {:action=>"show", :controller=>"users", :id=>nil} missing required keys: [:id]

The index.html.erb

<% @ribbits.each do |ribbit| %>
    <div class="ribbitWrapper">
        <a href="<%= user_path ribbit.user %>">
            <img class="avatar" src="<% ribbit.user.avatar_url %>" />
            <span class="name"> <%= ribbit.user.name %> </span>
        </a>
        @<%= ribbit.user.username %>
        <span class="time"><%= time_ago_in_words(ribbit.created_at) %></span>
        <p> <%= ribbit.content %></p>
    </div>
<% end %>

The users controller:

    def new
    @user = User.new
end

def create
  @user = User.create(user_params)

  if @user.save
    session[:user_id] = @user.id
    redirect_to @user, notice: "Thank you for signing up!"
  else
    render 'new'
  end
end

def show
    @user = User.find(params[:id])
    @ribbit = Ribbit.new
end

The ribbits controller

def index
    @ribbits = Ribbit.all
    @ribbit = Ribbit.new
end

def create
  @ribbit = Ribbit.create(user_ribbits)
  @ribbit.user_id = current_user.id

  if @ribbit.save
      redirect_to current_user 
  else
      flash[:error] = "Problem!"
      redirect_to current_user
  end
end

private

def user_ribbits
  params.require(:ribbit).permit(:content, :userid)
end

def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

helper_method :current_user

And also, the routes file

  resources :sessions
  resources :users
  resources :ribbits

  get 'logout', to: 'sessions#destroy', as: 'logout'

  root to: 'users#new'

Would really appreciate the help!

Upvotes: 0

Views: 467

Answers (1)

Joe Kennedy
Joe Kennedy

Reputation: 9443

As we discovered in the comments to the question, some of the @ribbits do not have user_id set.

To address your further question of "How do I connect user_id with my ribbits, my guess is that you have ribbits with user_id null because your user_ribbits method permits :userid rather than :user_id. This is assuming of course that you're properly passing user_id from your view to your controller on the creation of a ribbit.

In order to ensure that ribbits contain a user_id, you can add the following to your Ribbit model (ribbit.rb):

validates :user_id, presence: true

If there are other issues, this should at the very least prevent you from creating a ribbit without a user_id.

I hope this helps!

Upvotes: 1

Related Questions