Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails instance variable not passing to view with "Render"

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.

like image 845
gematzab Avatar asked Feb 14 '26 08:02

gematzab


1 Answers

Add @categories = Category.all in create method:

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
    @categories = Category.all
    render :action=> "new_pack", :id => @user.id
  end
end 
like image 165
zishe Avatar answered Feb 17 '26 01:02

zishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!