0
votes

I am having 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 View:

<li><%= render 'directory/bookmarks', zoo: zoo %></i></li>

Then the directory/bookmarks partial:

<% 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| %>
         <%= 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 %>   

Anyway, the problem is the zoo.id on the 3rd line is not being evaluated. I get this error.

undefined method `model_name' for NilClass:Class

The weird part is that locals are being read on the page.

If I place this code snippet <%= zoo.id %> anywhere on the page, I get the id. Then, the find_by_zoo_id is being evaluated also...if I put 255 a hardcoded number, it works. Or if I set it to a variable, @id = 255 and then pass in the @id, it works.

The zoo.id only does not work inside of the form_for for some reason. If I set it to an instance variable on the page, @id = zoo.id, that doesn't work either.

Any ideas? I'm sure it is something minor.

EDITED:

The relationship is has_many :through. Forgot to mention, I use this code for a different association in the same application and it works fine.

2
How are current_user and bookmarks associated. Is this a has_many...through relationship? I think the problem here is the zoo.id you're passing does not belong to the current_user. There might be a bookmark with that zoo.id but it just does not belong to the current_user. Is that possible? - vee
Hey, I check this in the console: User.find(2).bookmarks.where(zoo_id: 255) This exists. - miler350

2 Answers

0
votes

That error you're getting suggests current_user.bookmarks.find_by_zoo_id(zoo.id) is nil. find_by_zoo_id might be returning you nothing

0
votes

Of course it was -- I was iterating through a list of zoos with bookmarks, but not all of them would be bookmarked by the user. I just had to add an additional condition.

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