Nei*_*eil 4 ruby ruby-on-rails nested-attributes
我有以下关联:
#models/contact.rb
class Contact < ActiveRecord::Base
has_many :contacts_teams
has_many :teams, through: :contacts
accepts_nested_attributes_for :contacts_teams, allow_destroy: true
end
#models/contacts_team.rb
class ContactsTeam < ActiveRecord::Base
belongs_to :contact
belongs_to :team
end
#models/team.rb
class Team < ActiveRecord::Base
has_many :contacts_team
has_many :contacts, through: :contacts_teams
end
Run Code Online (Sandbox Code Playgroud)
Acontact应始终至少有一个关联的团队(在 的丰富联接表中指定contacts_teams)。
如果用户尝试创建没有关联团队的联系人:应该抛出验证。如果用户尝试删除联系人的所有关联团队:应引发验证。
我怎么做?
我确实查看了嵌套属性文档。我还看了这篇文章和这篇文章,它们都有些过时了。
完成:我正在使用nested_form_fieldsgem 将新的关联团队动态添加到联系人。这是表单上的相关部分(有效,但目前无法验证是否至少有一个团队与联系人相关联):
<%= f.nested_fields_for :contacts_teams do |ff| %>
<%= ff.remove_nested_fields_link %>
<%= ff.label :team_id %>
<%= ff.collection_select(:team_id, Team.all, :id, :name) %>
<% end %>
<br>
<div><%= f.add_nested_fields_link :contacts_teams, "Add Team"%></div>
Run Code Online (Sandbox Code Playgroud)
因此,当未单击“添加团队”时,不会通过与团队相关的参数传递任何内容,因此不会contacts_team创建任何记录。但是当点击“添加团队”并选择一个团队并提交表单时,类似这样的事情会通过参数传递:
"contacts_teams_attributes"=>{"0"=>{"team_id"=>"1"}}
Run Code Online (Sandbox Code Playgroud)
小智 6
在 Rails 5 中,这可以使用:
validates :contacts_teams, :presence => true
Run Code Online (Sandbox Code Playgroud)
这对创建和更新 acontact进行验证:确保至少有一个关联contacts_team。当前存在导致用户体验不佳的边缘情况。我在这里发布了这个问题。在大多数情况下,虽然这可以解决问题。
#custom validation within models/contact.rb
class Contact < ActiveRecord::Base
...
validate :at_least_one_contacts_team
private
def at_least_one_contacts_team
# when creating a new contact: making sure at least one team exists
return errors.add :base, "Must have at least one Team" unless contacts_teams.length > 0
# when updating an existing contact: Making sure that at least one team would exist
return errors.add :base, "Must have at least one Team" if contacts_teams.reject{|contacts_team| contacts_team._destroy == true}.empty?
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7310 次 |
| 最近记录: |