ruby-on-railsform-helpers

rails form helper color_field not pulling value through


I have class named 'Color' which inherits from String, it takes and returns a color hex string.

I have the following model

class Category < ActiveRecord::Base

  def color
    Color.new(self[:color])
  end

end

And I have the following view for the category edit form:

<%= form_for @category, url: @category do |f| %>
  <%= f.label :color %>:
  <%= f.color_field :color %>
<% end %>

Whatever I set the 'color' to for the Category, the color_field always returns black. I'm guessing that nil is getting passed to the field and black is just the default value?

The odd thing is if I change the color_field to text_field the hex string pulls through as expected. If I call @category.color, @category::color, @category[:color] or @category.send :color I also receive the hex string as expected so I can't work out where the black (or nil) is coming from.


Solution

  • color_field

    Here is an example

    f.color_field :color
    
    # => <input id="color" name="color" type="color" value="#000000" />
    

    So by default it takes value="#000000" to override it need to pass explicitly

    <%= f.color_field :color, value: @category.color%>
    

    Reference: - http://railsdoc.com/references/color_field

    *correct me if i'm wrong***