[英]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
請指導如何解決這個問題。 在此先感謝您的幫助:)
請改變你的模型方法寫這個
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.