Saturday, April 21, 2012

Re: [Rails] NilClass in Partial

On 21 April 2012 05:04, Karl McCollester <lists@ruby-forum.com> wrote:
> I appreciate your help in advance; I feel like the issue is staring me
> in the face!
>
> I have two models: event and topic
>
> /models/event.rb:
> class Event < ActiveRecord::Base
>  ..
>  has_many :topics
>  ..
>
>
> /models/topic.rb:
> class Topic < ActiveRecord::Base
>  belongs_to :event
> end
>
> I'm successfully showing the dependent topics with the event:
> /views/events/show.html.erb:
>
> ..
> <table>
> <%@event.topics.each do |topic| %>
> <tr>
>  <td> <%= topic.Name %> </td>
>  <td> <%= topic.Description %></td>
> </tr>
> <% end %>
> </table>
> ..
>
> When I attempt to edit the record that I can successfully show, I get:
>
> Showing /views/events/_topic.html.erb where line #2 raised:
>
> undefined method `new_record?' for nil:NilClass
> Extracted source (around line #2):
>
> 1: <div class="topic">
> 2:   <% new_or_existing = topic.new_record? ? 'new': 'existing' %>
> 3:   <% prefix = "event[#{new_or_existing}_topic_attributes][]"%>
> 4:
> 5:   <% fields_for prefix, topic do |topic_form| -%>
>
> The partial is rendered in edit.html.erb:
>
> <h1>Editing tag</h1>
>
> <%= render 'form' %>
>      <div id="topicContentArea">
>        <%= render 'topic', :collection => @event.topics %>

I have not used :collection to pass something like @event.topics
rather than a simple variable such as @topics, so wonder whether this
works as you expect. You could try
<%= render 'topic', :collection => @event.topics, :as => :topic %>
in order to force the variable name in the partial.

Colin

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate