简体   繁体   中英

how to define extra method for rails form text_field

After removing dimensions from my table, my scaffolded view hit this error: undefined method 'dimensions' for this code:

<div class="field">
    <%= f.label :dimensions %><br>
    <%= f.text_field :dimensions %>
  </div>

I want to keep this dimention field in the form and in the controller I want to split this string into length, width, height.

Now what should I do?

Try this into your model to keep this attribute dimensions as virtual attributes

 Class ModelName < ActiveRecord::Base
   attr_accessor :dimensions
 end

You need a virtual attribute, which is done using attr_accessor

attr_accessor is a ruby method for creating getter and setter methods. This basically means you're able to create a series of virtual attributes for use in your models

Class Table < ActiveRecord::Base
  attr_accessor :dimensions
end

If you only want to use it in the controller then instead of using f.text_field :dimensions , use text_field_tag :dimensions . You can access this attribute in the action directly by using params[:dimensions]

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