【发布时间】:2014-07-30 01:50:53
【问题描述】:
我的模型中有多个可用的社交网络:
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
我想手动声明使用的种类。也许我需要替代 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 %>
但我只为所有四个 ID 保存并显示了一个值。
在对每个单独的项目执行 fields_for 时,我得到 repeated kinds and repeated values
注意:与此个人资料表单相关联的每种类型都应该只有一个。
我相信我需要使用find_or_create_by 之类的东西来确保只制作每种类型的一个并将其加载到编辑器中,因为 fields_for 只是按照保存顺序加载所有内容。也许展示了这个Rails find_or_create by more than one attribute? 可以与kind 一起使用。
我需要确保产品只会保存每种产品中的一种以及在您编辑时;它将按种类正确加载,而不仅仅是任何belonging to。
由于在我的示例中,所有四个都将显示保存在编辑页面的第一个字段中的内容,很明显它目前不能确保 kind。
我想在我的application_controller.rb 中使用类似的东西
def one_by_kind(obj, kind)
obj.where(:kind => kind).first_or_create
end
如何用这个替换 fields_for 方法?
【问题讨论】:
标签: ruby-on-rails rails-activerecord polymorphic-associations