如何在rails 4中创建一个新的belongs_to关联模型

时间:2015-03-30 22:23:29

标签: ruby-on-rails model devise associations

我有2个模型,房东和属性,属性属于一个奇异的房东,房东有很多属性。

我想在我作为房东登录时建立一个新属性,但目前它正在抛出NoMethodError (undefined method 'landlords_id' for #<Property:0x007fa74060a420>)

我的代码中没有landlords_id,我正在撕开我的头发。

这是我的房东模特

class Landlord < ActiveRecord::Base
  has_many :properties

  devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable,:authentication_keys => [:username]   
end

这是我的房产模型

class Property < ActiveRecord::Base

  belongs_to :landlord
end

这是我的properties_controller.rb

class PropertiesController < ApplicationController
  before_action :authenticate_landlord!
  layout 'dash'

  def create
    @property = current_landlord.properties.build(property_params)
    @landlord = current_landlord

    if @property.save    

      redirect_to :controller=>'invites', :action => 'new' ,:landlord_id => @landlord.slug, :property_id => @property.slug

    else
      flash.now[:error] ="Failed To Add Property, Please Check Your Input"
      render 'new'
    end

  end

错误明确指向第28行,即if @property.save

让我相信  @property = current_landlord.properties.build(property_params)

对于#`

遇到了undefined method landlords_id'

但我甚至不知道它的来源。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

您使用landlords_id代替landlord_id(单数)的代码中的某些位置。第一个搜索地点:views/properties/new.*views/properties/_form.*