2

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.

1 Answer 1

9

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Zishe thank you for your answer. This is correct but could you please give me a brief explanation of this solution? When I am rendering the "new_pack" action they get loaded the instance variables of the create action??
Of course. render action: is the same as render template, you can see it here. It's not possible to somehow trigger other action, only to redirect. And when you just render that template you should have all necessary data, including @categories

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.