Search code examples
rubyruby-on-rails-4tagsslim-lang

Rails 4: Additional form field


That is how my new/edit message form looks like (I'm using slim):

= form_for(@message) do |f|
  = f.label :message
  br
  = f.text_area :content
  br
  = f.submit 'Submit'

Is there a way to send additional field through form (Which is not defined in any model?). I want to use it in 'create' method inside messages controller.


Solution

  • If using Rails 4 you can create a custom accessor in the model:

    attr_accessor :content

    and it will not be saved to database.

    In Rails 5 there's a specific macro about that that can also typecast the attribute for reading.

    Anyway, ensure that the attribute is also on the list of whitelisted parameters if using http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html