Property#new中的noMethodError

时间:2017-12-03 02:46:08

标签: ruby-on-rails ruby-on-rails-4

我有一个问题要找出这个错误的来源。

我收到此错误:

enter image description here

我不确定,问题与我在视图中命名文件夹有关,我将其命名为属性...而不是属性(我已经尝试更改它但我仍然收到错误)

enter image description here

这就是我的模型的样子

class PropertyController < ApplicationController
  def index
    @properties = Property.all
  end

  def new
    @property = Property.new
  end

  def create
    @property = Property.new(property_params)
    if @property.save?
      flash[:notice] = 'Property was successufully created.'
      redirect_to property_path(@property)
    else
      render :new
    end
  end

  private
  def property_params
    params.require(:property).permit(:address, :price, :description, 
:bedrooms, :bathrooms, :type, :sqft, :lot, :year_built)
  end
end

这是我的控制者:

property_controller.rb

_form.html.erb
     <% if @property.errors.any? %>
       <h3>The following errors prevented the addition of this property.
      </h3>
      <ul>


    <% @property.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    <% end %>

    <%= form_for @property do |f| %>
      <div class="form-group">
        <%= f.text_field :address, required: true, placeholder: "Address", 
    class: "form-control"%>
      </div>
      <div class="form-group">
        <%= f.text_field :price, required: true, placeholder: "Price", 
    class: "form-control"%>
      </div>
      <div class="form-group">
        <%= f.text_area :description, required: true, placeholder: 
    "Description", class: "form-control"%>
      </div>
      <div class="form-group">
        <%= f.button :submit, class: "btn btn-success" %>
      </div>
    <% end %>

new.html.erb

    <h3>Add new Property:</h3>

    <%#= render 'form' %>

和我的观看文件

#define N 100

vector<int> get_random_numbers()
{
    random_device rd;  //Will be used to obtain a seed for the random number engine
    mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    uniform_int_distribution<> dis(0, N);

    vector<int> randoms(N);
    for (int i = 0; i < N; i++)
    {
        randoms[i] = dis(gen);
    }
    return randoms;
}

void insert_in_lists()
{
    vector<int> randoms = get_random_numbers();
    sort(randoms.begin(), randoms.end());
    list<int> l(randoms.begin(), randoms.end());
    for (list<int>::iterator p = l.begin(); p != l.end(); p++)
    {
        cout << *p << endl;
    }
}

似乎错误与表单有关,因为如果我将表单注释掉,new.html.erb显示正常。任何帮助将不胜感激。

rake routes | grep属性

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您声明form_for而未明确定义url,则Rails会猜测您想要的路线。在您的情况下,由于@property是一个新实例(未加载),因此Rails希望POST转到properties_path。这只是Rails惯例。

您最有可能的解决方案就是将resources :properties添加到您的routes.rb文件中。如果您粘贴文件,我们可以提供更多信息,说明为什么这是必要的。

<强>更新

Rails期望表名(以及路由)是模型名称的复数形式。因此,您的Property模型具有properties表格和路线。使用resources :properties(复数)遵循Rails约定,让一切都很好地协同工作。