加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 验证表单中是否存在嵌套属性

发布时间:2020-12-17 02:56:18 所属栏目:百科 来源:网络整理
导读:我有以下协会: #models/contact.rbclass Contact ActiveRecord::Base has_many :contacts_teams has_many :teams,through: :contacts accepts_nested_attributes_for :contacts_teams,allow_destroy: trueend#models/contacts_team.rbclass ContactsTeam Ac
我有以下协会:

#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

联系人应始终至少有一个关联的团队(在contacts_teams的富联接表中指定).

如果用户尝试创建没有关联团队的联系人:应该抛出验证.如果用户尝试删除所有联系人的关联团队:应该抛出验证.

我怎么做?

我确实看过nested attributes文档.我还看了this article和this article这两个都有点过时了.

完成:我使用nested_form_fields gem动态地向联系人添加新的关联团队.以下是表单上的相关部分(有效,但目前尚未验证至少有一个团队与该联系人关联):

<%= 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>

因此,当未单击“添加团队”时,没有任何内容通过与团队相关的参数传递,因此不会创建contacts_team记录.但是当点击“添加团队”并选择团队并提交表单时,这样的事情会通过参数传递:

"contacts_teams_attributes"=>{"0"=>{"team_id"=>"1"}}

解决方法

在Rails 5中,这可以使用:

validates :contacts_teams,:presence => true

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读