【问题标题】:Cannot save new Rails 3 ActiveRecord model无法保存新的 Rails 3 ActiveRecord 模型
【发布时间】:2012-03-24 20:51:51
【问题描述】:

我正在开发一个允许用户创建寻宝游戏的网络应用程序。麻烦的是,我似乎无法说服 Rails 保存新的狩猎。这是我的设置。知道我做错了什么吗?

型号:

class Hunt < ActiveRecord::Base
  attr_accessible :name

  validates :name,  :presence => true,
                    :length   => { :maximum => 50 } ,
                    :uniqueness => { :case_sensitive => false }
end

控制器:

class HuntController < ApplicationController

  def index
     @title = "All Hunts"
     @hunts = Hunt.order("name ASC")     
  end

  def show
    @hunt = Hunt.find(params[:id])
    @title = @hunt.name    
  end

  def new
    @hunt = Hunt.new
    @title = "New Hunt"  
  end

  def create
    @hunt = Hunt.new(params[:hunt]) #fixed type (used to be this: Hunt.new(params[:id]) )
    if @hunt.save
      flash[:success] = "Hunt created!"
      redirect_to index
    else
      @title = "New Hunt"
      render 'new'

    end

    ...

end

查看

    <h1>Sign up</h1>

    <%= form_for(@hunt) do |f| %>

        <div class="field">
         <%= f.label :name %><br />
         <%= f.text_field :name %>
        </div>

      <div class="actions">
        <%= f.submit "Sign up" %>
      </div>
    <% end %>

路线

MyChi::Application.routes.draw do


  get "hunts/index"
  get "hunts/new"
  get "hunts/create"  
  get "hunts/show"
  get "hunts/list"  
  get "hunts/edit"
  get "hunts/delete"

  match '/hunts', :to => 'hunts#index'

  resource :hunts

  .....

  root :to => "pages#home"

  match ':controller(/:action(/:id(.:format)))'

编辑:我应该提到,当添加新的搜索时,应用会将用户重定向到 Index,但没有成功的 Flash 通知。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    在您的创建操作中,将 Hunt.new(params[:id]) 更改为 Hunt.new(params[:hunt])

    【讨论】:

    • 没看到那个类型。谢谢。不幸的是,这不是麻烦制造者。我修正了错字,但仍然有问题。
    • 你的控制器类应该是复数“HuntsController”,你能检查一下日志,看看你是否得到任何错误。
    • 所以我将“HuntController”更改为“HuntsController”,更新了路由文件并重新启动了服务器。不幸的是,它并没有改变我的应用程序的行为。关于可能导致此问题的任何其他想法?
    • 在你的路线中你有资源吗:狩猎
    • 是的。我发布了路线文件的相关部分。
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2013-07-04
    • 1970-01-01
    相关资源
    最近更新 更多