简体   繁体   中英

How to call model method in rails controller

Hi I have to call model method in my controller and view. So for this I had done this:

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

and in 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 %>

whem am giving this it gives me error ActiveRecord::DangerousAttributeError in ProductsController#new Please guide how to solve this. Thanks in advance for help :)

use this gem:

gem 'safe_attributes'

then

bundle install

also see gem's documentation and you are done :)

Please change your model method writes this

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

and you are using field model_name so just because of this its giving an error of Dangerous attributes error so please change it to name hope this will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM