【问题标题】:undefined method `model_name' for NilClass:Class when trying to create a record in my database尝试在我的数据库中创建记录时 NilClass:Class 的未定义方法“model_name”
【发布时间】:2012-05-04 18:18:09
【问题描述】:

我的 Rails 应用有问题。

当我尝试在我的 clients 表中创建一个新的 client 时,我收到了这个错误 => undefined method model_name for NilClass:Class

它告诉我错误出现在我的第 2 行的显示视图中。

1: <%- model_class = @client.class -%>
2: <h1><%=t '.title', :default => model_class.model_name.human %></h1>
3: 
4: <p>
5:   <strong><%= model_class.human_attribute_name(:name) %>:</strong><br>

这是我的节目视图..

<%- model_class = @client.class -%>
<h1><%=t '.title', :default => model_class.model_name.human %></h1>

<p>
  <strong><%= model_class.human_attribute_name(:name) %>:</strong><br>
  <%= @client.name %>
</p>
<p>
  <strong><%= model_class.human_attribute_name(:detail) %>:</strong><br>
  <%= @client.detail %>
</p>
<p>
  <strong><%= model_class.human_attribute_name(:more_detail) %>:</strong><br>
  <%= @client.more_detail %>
</p>
<p>
  <strong><%= model_class.human_attribute_name(:more_details) %>:</strong><br>
  <%= @client.more_details %>
</p>

<div class="form-actions">
  <%= link_to t('.back', :default => t("helpers.links.back")),
              clients_path, :class => 'btn'  %>
  <%= link_to t('.edit', :default => t("helpers.links.edit")),
              edit_client_path(@client), :class => 'btn' %>
  <%= link_to t('.destroy', :default => t("helpers.links.destroy")),
              client_path(@client),
              :method => 'delete',
              :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')),
              :class => 'btn btn-danger' %>
</div>

这是我的控制器 =>

类 ClientsController

  respond_to :html

  def index
    @clients = Client.all
    respond_with (@clients)
  end

  def new
    @clients = Client.new
    respond_with (@clients)
  end

  def create
    @clients = Client.new(params[:name])
    if @clients.save
      flash[:notice] = "Client successfully created"
    end
    respond_with(@clients)
  end

  def destroy
  @clients = Client.find(params[:id])
  @clients.destroy
  flash[:notice] = "Client has been removed."
  respond_with(@clients)
  end

end

我看不出问题出在哪里?

我最近安装了 rails-twitter-bootstrap gem,但认为这不会有太大影响。

【问题讨论】:

  • 你在创建模型后有没有rake db:migrate
  • 是的,当我生成它时,我的迁移就完成了。

标签: ruby-on-rails ruby-on-rails-3 twitter-bootstrap


【解决方案1】:

您正在控制器中设置@clients 的值(末尾带有s)并在您的视图中仅访问@client 变量,即没有s。解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多