控制器#new动作中的NoMethodError

时间:2014-07-21 21:27:42

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

解决方案可能很明显,但我查看了Stackoverflow上的很多帖子,无法解决此错误。

app/views/sellers/_form.html.erb where line #16 raised:
undefined method `name' for #<Seller:0x007fbedb5f3ce0>

    Extracted source (around line #16):   

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

_form.html.erb

的开头
<%= form_for(@seller) do |f| %>
  <% if @seller.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@seller.errors.count, "error") %> prohibited this seller from being saved:</h2>
      <ul>
        <% @seller.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

sellers_controller (编辑:这是下面提到的控制器)

class SellersController < ApplicationController
  def new
    @seller = Seller.new
  end
end

schema.rb

create_table "sellers", force: true do |t|
  t.string   "name"
  t.string   "person_type"
  t.string   "rep_first_name"
  t.string   "rep_last_name"
  t.date     "rep_birthday"
  t.string   "rep_nationality"
  t.string   "rep_country_of_residence"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "mp_id"
  t.integer  "mp_walletid"
end

seller.rb

class Seller < User
  has_many :resas
  has_many :buyers, :through => :resas
  validates :name, :person_type, :rep_first_name, :rep_last_name, :rep_birthday, :rep_nationality, :rep_country_of_residence, presence: true
  validates :name, length: { maximum: 255 }
  validates :rep_first_name, :rep_last_name, length: { maximum: 100 }
  validates :rep_nationality, :rep_country_of_residence, length: { is: 2 }
  def seller?
    self.is_a?(Seller)
  end
end

user.rb

class User < ActiveRecord::Base
  has_one :seller, dependent: :destroy
  accepts_nested_attributes_for :seller
  has_one :buyer, dependent: :destroy
  accepts_nested_attributes_for :buyer
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  def type
    self.type
  end
end

1 个答案:

答案 0 :(得分:4)

错误:

undefined method 'name' for #<Seller:0x007fbedb5f3ce0>

如果没有为name模型定义属性Seller,则会发生

。 要解决此问题,请将name作为字段添加到sellers表,或根据您的要求将其设置为Seller模型中的虚拟属性。

<强>更新

看起来您正在尝试实现单表继承(STI)。

如果是这种情况,那么你应该只有一个单个表,即用户,其中包含一个名为type的字段,用于识别孩子{{1}在你的情况下。

我强烈建议阅读@ tadman的回答Single Table Inheritance to refer to a child class with its own fields。它肯定会帮助您设置适当的STI。