2011-07-09 46 views
1

我开始提出不同的问题,关于一个collection_select,但我发现这不是问题。 这个特定的模型根本不会保存任何数据。它只是忽略参数中的值。我只能用NULL值保存新记录(时间戳字段除外)。新记录没有保存任何值

看到我的评论为我最新的尝试解决它。

我用便利的scaffold命令生成了一些模型。现在我试图将文本框更改为collection_select,以将新实体链接到正确的相关链接。

使用rails 3.1RC4(希望这不是一个bug)。

在我使用下面的代码_form.html.erb:

<div class="field"> 
    <%= f.label :category_id %><br /> 
    <%= f.collection_select(:category_id, Admin::Category.all, :id, :name) %> 
    </div> 
    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    ...all other items... 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 

后,我点击提交按钮,我收到错误消息。它说名称和永久链接不符合验证。但我不明白,因为在日志文件中,我发现这个:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"my token is here", "admin_branche"=>{"category_id"=>"3", "name"=>"Verzekeraars", "permalink"=>"verzekeraars", "visible"=>"1"}, "commit"=>"Create Branche"} 

对我来说,似乎params包含所有需要的值。

为了完整起见,我会在下面发布我的创建方法和模型。

到目前为止,我尝试在collection_select和f.coll之间来回切换,但没有成功。根据日志,目前的设置对我来说似乎最合适。 我也搜索了很多,但一直没能找到答案。本网站上的问题2280106看起来是一样的,但它必须与我在模型中注释过的attr_accessible(我之后重新启动服务器并重试,只是为了确定)。

非常感谢帮助!

branche.rb:

class Admin::Branche < ActiveRecord::Base 

# attr_accessible :name, :permalink 

    #relationships 
    has_many :courses, :as => :parent 
    belongs_to :category 

    #validations 
    validates :name, :presence => true, :length => {:maximum => 255} 
    validates :permalink, :presence => true, :length => { :within => 4..25 } 

end 

创建控制器动作:

def create 
    @admin_branch = Admin::Branche.new(params[:admin_branch]) 

    respond_to do |format| 
     if @admin_branch.save 
     format.html { redirect_to @admin_branch, notice: 'Branche was successfully created.' } 
     format.json { render json: @admin_branch, status: :created, location: @admin_branch } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @admin_branch.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
+0

只是可以肯定,我删除所有与此模型相关的文件再次运行rails g scaffold命令,但它仍然不会拾取参数。其他模式工作正常,但...任何帮助? – Kobes

回答

0

在控制器,你这样做是:

@admin_branch = Admin::Branche.new(params[:admin_branch]) 

你应该这样做:

@admin_branch = Admin::Branche.new(params[:admin_branche]) 

如果查看请求参数,属性位于“admin_branche”下,而不是“admin_branch”。

我认为应该解决您的问题,如果没有,请让我们知道。

+0

哇,非常感谢!完全做到了。我觉得愚蠢的没有注意到(凝视几个小时后)。我仍然不明白为什么默认的脚手架生成器没有把它做对,但它可能与单数/复数形式有关。情况可能如此。我生成了一个Branche脚手架,而英语中正确的单数形式最终没有-e。非常混乱,因为荷兰单数形式是我拼写出来的......对不起! – Kobes

+0

没什么可抱歉的,错别字发生在每个人身上。我很高兴它的工作:) – henrikhodne

0

如果您有与生成的语调问题,你可以完全自主的他们在config /初始化/是inflections.rb

只需添加这样的事情:

ActiveSupport::Inflector.inflections do |inflect| 
     inflect.irregular 'branch', 'branches' 
    end