Basic rails question..I have the following: a user has many packs and a pack belongs to a category. In the new pack form I want make a select field with the pack's categories. I have the following code :
def new_pack
@pack=Pack.new()
@user= User.find(params[:id])
@categories = Category.all
end
def create
@pack=Pack.new(pack_params)
@user= User.find(params[:user_id])
if @pack.save
@user.packs << @pack
flash[:notice]="Thank you!"
redirect_to(:action=>'attempt_activation', :id=> @pack.id)
else
render :action=> "new_pack", :id=>@user.id
end
end
And in my view:
<%= form_for(:pack, :url=>{:controller=> "packs", :action=>'create', :user_id=> @user.id}) do |f| %>
<h5>Registration takes less than 2 minutes.</h5>
<label>Title<b style="color:red;">*</b>
<%= f.text_field(:title, :placeholder=>"") %>
</label>
<label>Category<b style="color:red;">*</b>
<%= f.select(:category_id, @categories.map {|s| [s.title, s.id]}, :selected=> @categories.second) %>
...
THE PROBLEM is that if there are errors at the form and and the new_pack action has to be rendered again it throws an error:
ActionView::Template::Error (undefined method `map' for nil:NilClass):
</div>
<div class="large-4 columns">
<label>Category
<%= f.select(:category_id, @categories.map {|s| [s.title, s.id]}, :selected=> @pack.category) %>
</div>
Why is this happening? render is used to render a particular view using the instance variables available in the action but here is not loading again the @categories.
Thank you.