Pregunta

So I have the following erb that works:

<ul class="list-group">
  <%- @user_skills.each do |user_skill| %>
    <li class="list-group-item"><%= user_skill.skill.name %></li>
  <% end %>
</ul>

<%= semantic_form_for current_user.user_skills.new do |f| %>
  <%= f.inputs %>
  <%= f.actions  %>
<% end %>

In my controller, I have a @user_skills = current_user.user_skills. Once I swap the two blocks:

<%= semantic_form_for current_user.user_skills.new do |f| %>
  <%= f.inputs %>
  <%= f.actions  %>
<% end %>

<ul class="list-group">
  <%- @user_skills.each do |user_skill| %>
    <li class="list-group-item"><%= user_skill.skill.name %></li>
  <% end %>
</ul>

It raises an error like this: undefined methodname' for nil:NilClass`. So I'm guessing the form builder is somehow overwriting the user_skill inside the ul block. But why and how do I resolve the problem? It doesn't seem to be a formtastic issue, since I also used the native form builder.

UPDATE: So I found out that the @user_skills array actually contains the just created user_skill, which hasn't been persisted and do not have a #skill_id or #skill.name! And if I do UserSkill.new at the start of the form, then the @user_skills array will be ok. Maybe there is a caching layer in activerecord that will automatically include just created objects into the query. Or is this a bug?

¿Fue útil?

Solución

The call current_user.user_skills.new adds a blank user_skill to the has_many association of current_user. Since @user_skills is simply a reference to current_user.user_skills, the blank instance is included in the the unordered list when iterating after initializing the new user_skill record.

You'd be better off simply initializing a new user_skill in the form:

<%= semantic_form_for UserSkill.new do |f| %>
  <%= f.inputs %>
  <%= f.actions  %>
<% end %> 

Then, in the create action of your UserSkillsController, associate the user_skill attributes with the current_user. A bare-bones version could look something like:

def create
  @user_skill = current_user.user_skills.create(params[:user_skill])
  respond_with @user_skill
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top