【问题标题】:How to call model method in rails controller如何在rails控制器中调用模型方法
【发布时间】:2015-05-15 10:43:51
【问题描述】:

您好,我必须在我的控制器和视图中调用模型方法。所以为此我做了这个:

category.rb

def self.category_list
    category = self.all.collect { |m| [m.name, m.id] }
    return category
end

products_controller.rb

def new
    @product = Product.new
    @category = Category.category_list
end

在 products/new.html.erb 中

<%= form_for @product, action: "create", :html => {:class => "form-group"} do |f| %>
        <div class="fields">
          <%= f.label :model_name %>
          <%= f.text_field :model_name, :class => "form-control" %>
        </div>
        <div class="fields">
          <%= f.label :model_number %>
          <%= f.text_field :model_number, :class => "form-control" %>
        </div>
        <div class="fields">
          <%= f.label :model_number %>
          <%= f.select(:category_id, @category, :prompt => 'Select') %>
        </div>
        </br>
        <div class="actions">
          <%= f.submit "Submit", :class => "btn btn-success" %>
        </div>
<% end %>

我给这个它给了我错误ActiveRecord::DangerousAttributeError in ProductsController#new 请指导如何解决这个问题。提前感谢您的帮助:)

【问题讨论】:

  • 你有什么问题?
  • category_list 方法应该是简单的 oneliner:pluck(:name, :id)。在 Ruby 中,最后一行是方法返回的内容,您无需在此处指定 return
  • 你的productscontroller#new 没有定义@inventory 它在哪里初始化?
  • 抱歉打错了
  • 你正在使用rails 3 ?

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


【解决方案1】:

使用这个宝石:

gem 'safe_attributes'

然后

bundle install

另见gem's documentation,你就完成了:)

【讨论】:

    【解决方案2】:

    请改变你的模型方法写这个

    def self.category_list
        Category.all.collect { |c| [c.name, c.id] }
      end
    

    并且您正在使用字段模型名称,因此它给出了危险属性错误的错误,因此请将其更改为名称,希望这会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多