Jump to content

The ultimate community for Ruby on Rails developers.


Photo

undefined method `model_name' for NilClass:Class with Partials and Form_for


  • Please log in to reply
1 reply to this topic

#1 miler350

miler350

    Passenger

  • Members
  • 2 posts

Posted 13 December 2013 - 08:05 AM

I am having what seems like a weird issue where my rails application seemingly isn't reading the local variable passed to the partial, but only inside of form_for.

I have a set up a button where a user can bookmark an object, let's call it zoo.

The code looks like this:

Zoo Listing index.html.erb:

<% @zoos.each_with_index do |zoo,i| %>
  <%= render :partial => 'zoo_listing', :locals => {zoo: zoo} %>
<% end %>
Then on the listing page, I render a partial for the bookmark code.
 
<li><%= render 'directory/bookmarks', zoo: zoo %></i></li>

My bookmark code is as follows:

<% if user_signed_in? %>
   <% if current_user.has_zoo_bookmarked_already? %>
      <%= form_for(current_user.bookmarks.find_by_zoo_id(zoo.id), html: { method: :delete }, remote: true) do |f| %>   ###the error is zoo.id on this line #####
         <%= button_tag do %>
            <button class="btn btn-lg btn-block btn-primary">remove bookmark
         <% end %>
      <% end %> 

<% else %>

  <%= form_for(current_user.bookmarks.build(zoo_id: zoo.id)) do |f| %>
    <%= f.hidden_field :zoo_id, value: zoo.id  %>
      <%= button_tag do %>
            <button class="btn btn-lg btn-block btn-primary">bookmark
      <% end %>
   <% end %>
<% end %>


<% else %>
<% end %>   

After the running this code, I get:

undefined method `model_name' for NilClass:Class

The specific zoo, is zoo number 255. If I use this code, it works, but obviously, this isn't what I need.

 <%= form_for(current_user.bookmarks.find_by_zoo_id(255), html: { method: :delete }, remote: true) do |f| %>

#### or this code ###

@id = 255
...
<%= form_for(current_user.bookmarks.find_by_zoo_id(@id), html: { method: :delete }, remote: true) do |f| %>

To sanity check, I test the local variable directly with this code, and it works.

<%= zoo.id %>      ####----> 255

So, sorry if this is too much code, but I can't figure out why the code <%= zoo.id %> evaluates but when passed to form_for I get an error. 

 

 

 



#2 miler350

miler350

    Passenger

  • Members
  • 2 posts

Posted 13 December 2013 - 07:03 PM   Best Answer

Solved.

<% if user_signed_in? %>
  <% if current_user.has_zoo_bookmarked_already? && current_user.bookmarks.find_by_zoo_id(zoo.id) %>
    #....





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users