Rails 关于 select_tag 的问题

metal · 2011年12月26日 · 最后由 huacnlee 回复于 2012年02月04日 · 3884 次阅读

我的表单中有 select_tag,提交一个有错误的表单,立马就报错。

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.map

如果包 select_tag 换成 text_field 就没有问题。

应该是 rails 无法将错误信息的 class 加在 select_tag 的外面

<div class="field_with_errors"></div>

还是 models 验证里有其他写法???

我想知道如何解决。

给出详细点的代码

new.html.erb

<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
    <div class="alert-message block-message error">
        <h2>提交时发现了以下错误:</h2>
        <ul>
            <% @post.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
<% end %>
<div class="clearfix">
    <%= f.label :category_id %>
    <div class="input">
        <%= f.select :category_id, options_from_collection_for_select(@category, :id, :name), :prompt => true %>
    </div>
</div>
....

posts_controller.rb

def new
    @post = Post.new
    @category = Category.all
    @title = "新建文章"
end
def create
    @post = Post.new(params[:post])
    if @post.save
        redirect_to :action => 'index' 
        flash[:notice] = "新建成功:)"
    else
        render action: "new"
    end
end

你确定错误来自那里? 我看你的错误比较像是因为 create 里面没有@category

#3 楼 @ywencn 就算我没有@category,我也可以创建成功。我没想过创建 category,只是用他来获取分类。 问题是其他栏位(例如标题,内容)如果不准确的就会报错,所有栏位都准确就会成功提交。

#4 楼 @metal no...没有@category不影响创建成功,只影响创建失败。。。因为失败的时候 render new,view 里面要这个变量,控制器里没给。。然后就保持了,你加上试试嘛

#5 楼 @ywencn 3Q,我检查了一次,确实是出在 render 这个问题上。。。来亲一个。

#5 楼 @ywencn 在进来感谢,解决了。。。哈哈。。我之前把 render action: => 'new'换成 redirect_to 就可以了。现在在 create 里加入@category = Category.all,搞定!!!原来这么简单。

不规范的命名 @category 应该用 @categories

需要 登录 后方可回复, 如果你还没有账号请 注册新账号