簡體   English   中英

如何在Rails控制器中調用模型方法

[英]How to call model method in rails controller

嗨,我必須在控制器中調用模型方法並進行查看。 為此,我這樣做了:

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錯誤ActiveRecord::DangerousAttributeError in ProductsController#new請指導如何解決這個問題。 在此先感謝您的幫助:)

使用這個寶石:

gem 'safe_attributes'

然后

bundle install

另請參閱gem的文檔 ,您就完成了:)

請改變你的模型方法寫這個

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

並且您正在使用model_name字段,因此正因為如此,它給出了Dangerous attribute error的錯誤信息,因此請將其更改為name,希望它能起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM