创建不保存数据库数据的操作

时间:2014-11-17 17:45:17

标签: ruby-on-rails ruby

我尝试将国家/地区列表保存到国家/地区的简单Ruby on Rails应用程序

这是我的新动作和创作动作

def new
    @country = Country.new
  end

  def create
    @country = Country.new(country_params)
    if @country.save
      flash[:notice] = "Country created successfully"
      redirect_to(:action => 'index')
    else
      render('new')
    end
  end

这里是私人参数

private
  def country_params
    params.require(:country).permit(:country_name)
  end

问题是国家/地区数据未被保存。我也没有收到任何错误。 create操作的开发日志如下所示:

Started GET "/countries/new?utf8=%E2%9C%93&authenticity_token=Df5d6Z0Gz9CkpHdgXypfR0dnxMkm0oImKP3Uq3UdP4Y%3D&country%5Bcountry_name%5D=Ukraine&commit=Create+country" for 127.0.0.1 at 2014-11-17 12:49:59 -0500
Processing by CountriesController#new as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Df5d6Z0Gz9CkpHdgXypfR0dnxMkm0oImKP3Uq3UdP4Y=", "country"=>{"country_name"=>"Ukraine"}, "commit"=>"Create country"}
  Rendered countries/new.html.erb within layouts/application (1.3ms)
Completed 200 OK in 115ms (Views: 114.5ms | ActiveRecord: 0.0ms)

我还添加了视图模板,因为添加视图后问题就开始了。

<div class= "container">
    <div class="row">
        <%= link_to("Back to list", {:action => 'index'}, :class => 'btn btn-primary margin-bottom') %>
    </div>
    <div class="row">
        <form class="form-inline">
            <%=  form_for(:country, :url => {:action => 'create'}) do |f| %>
            <%= f.label(:country_name, 'Name:', :class => 'control-label') %>
            <%= f.text_field(:country_name, :class => 'form-control') %>
            <%= submit_tag('Create country', :class=>'btn btn-success') %>
            <%end %>
        </form>
    </div>
</div>

<div>


</div>

添加了我使用

的默认路线
match ':controller(/:action(/:id))', :via => [:get, :post]

1 个答案:

答案 0 :(得分:0)

写在这里,因为在评论中我们没有得到很好的格式:

让我们更容易。我假设您的控制器被调用 CountriesController所以:删除默认路由&amp;在您的路线中添加resources :countries。接下来,采用以下形式:

<%=  form_for(@country, url: countries_path) do |f| %>
  ...
<% end %>

现在您应该在日志中看到您正在发出POST请求。您可以安装任何调试宝石,如pry-rails,并在创建操作binding.pry的开头键入,您将更好地了解正在进行的操作