Rails实例变量未通过"Render"传递给视图

gem*_*zab 2 render instance-variables ruby-on-rails-4

基本的轨道问题..我有以下内容:用户有很多包,一个包属于一个类别.在新包装表单中,我想要使用包装类别进行选择字段.我有以下代码:

      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 
Run Code Online (Sandbox Code Playgroud)

在我看来:

      <%= 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) %>
        ...
Run Code Online (Sandbox Code Playgroud)

问题是,如果表单中存在错误并且必须再次呈现new_pack操作,则会抛出错误:

       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>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?render用于使用动作中可用的实例变量呈现特定视图,但此处不再加载@categories.

谢谢.

zis*_*she 9

添加@categories = Category.all创建方法:

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 
Run Code Online (Sandbox Code Playgroud)