I have multiple social networks available in my model:
class Social < ActiveRecord::Base
enum kind: [ :twitter, :google_plus, :facebook, :linked_in, :skype, :yahoo ]
belongs_to :sociable, polymorphic: true
validates_presence_of :kind
validates_presence_of :username
end
I want to declare manually the kinds used. Maybe I need to have an alternative to fields_for?
<%= f.fields_for :socials do |a| %>
<%= a.hidden_field :kind, {value: :facebook} %> Facebook ID: <%= a.text_field :username, placeholder: "kind" %>
<%= a.hidden_field :kind, {value: :twitter} %> Twitter ID: <%= a.text_field :username, placeholder: "kind" %>
<%= a.hidden_field :kind, {value: :google_plus} %> Google ID: <%= a.text_field :username, placeholder: "kind" %>
<%= a.hidden_field :kind, {value: :linked_in} %> Linked In ID: <%= a.text_field :username, placeholder: "kind" %>
<% end %>
But I get just one value saved and displayed for all four IDs.
When doing a fields_for on each individual item I get repeated kinds and repeated values
NOTE: There should be only one of each kind associated with this profile form.
I believe that I need to use something like find_or_create_by
to ensure only one of each kind is made and loaded in the editor as the fields_for simply loads everything in the order they were saved. Maybe showing how this Rails find_or_create by more than one attribute? could be used with just kind
.
I need to ensure that product will only save one of each kind and when you edit it; it will load correctly by kind and not just any belonging to
.
Since in my example all four will display what was saved in the first field on the edit page it's clear it's not ensuring the kind
at the moment.
I'd like to use something like this in my application_controller.rb
def one_by_kind(obj, kind)
obj.where(:kind => kind).first_or_create
end
How would I substitute the fields_for method with this?