【问题标题】:Rails, nested attributes, invalidate parent with no childrenRails,嵌套属性,使没有子级的父级无效
【发布时间】:2012-12-19 01:59:24
【问题描述】:

假设我有 Post HABTM 标签,并且我正在通过嵌套属性使用批量分配。

我在 Post 模型中有这个:

accepts_nested_attributes_for :posts_tags, \
                              :reject_if => proc { |attrs| attrs.tag_id.blank? }

我在 Post 控制器中有这个:

def new
  @post = Post.new
  3.times { @post.posts_tags.build }
end

def create
  @post = Post.new(params[:post])
  @post.save
end

这在 Post 形式中:

<%= f.fields_for :tags do |tg| %>
  <%= tg.label :tag_id %>
  <%= tg.select :tag_id .... %>
<% end %>

一切都完美无缺,代码最少。帖子与被选中的标签相关联。

现在:如果我希望用户为他们的帖子选择至少一个标签怎么办。如何使未选择标签的帖子无效?什么是最优雅的解决方案?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 nested-attributes


    【解决方案1】:

    在 Post 模型中添加 validates_presence_of :tags 以强制用户选择标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2023-04-02
      相关资源
      最近更新 更多