【问题标题】:Building and creating related objects via the association: how to set the foreign key of a nested model?通过关联构建和创建相关对象:如何设置嵌套模型的外键?
【发布时间】:2011-11-29 12:09:04
【问题描述】:

我正在使用 Ruby on Rails 3.1.0。我正在尝试保存具有旨在存储父模型的外键的属性的嵌套模型。在创建父模型时,我想将该属性值设置为父模型id 值。

在我的模型中,我有:

class Article < ActiveRecord::Base  
  has_many :article_category_relationships
  has_many :categories,
    :through => :article_category_relationships

  # Accept nested model attributes
  accepts_nested_attributes_for :articles_category_relationships
end

class Category < ActiveRecord::Base
  has_many   :article_category_relationships
  has_many   :articles,
    :through => :article_category_relationships
end

# The join model:
class ArticleCategoryRelationship < ActiveRecord::Base
  # Table columns are:
  #   - article_id
  #   - category_id
  #   - user_id
  #   - ...

  belongs_to :category
  belongs_to :article
end

在我看来,我有以下几点:

...

<% @current_user.article_categories.each do |article_category| %>
  <%= check_box_tag 'article[articles_category_relationships_attributes][][category_id]', article_category.id, false %>
<% end %>

在我的控制器中,我有:

def create
  @article = Article.new(params[:article])

  ...
end

在我的例子中,article_id(与ArticleCategoryRelationship 嵌套模型相关)应该在创建Article 之后设置为@article.id 值,问题是Ruby on Rails 框架似乎不要在创建时设置该值。简而言之,考虑到我的情况,我想自动附加外键

要知道,表单提交时生成的params是:

"article"=>{"title"=>"Sample title", "articles_category_relationships_attributes"=>[{"category_id"=>"8"}, {"category_id"=>"9"}, {"category_id"=>"10"}] }

是否可以“自动”设置嵌套模型的外键 (article_id) ?如果是这样,我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    在我看来,你不能那样做。

    • 如果您要保存articles_category_relationships,您需要为每篇文章创建一个article_id。
    • 而且,当您保存文章时,r​​ails 将首先验证文章和所有子对象。这意味着 article.valid? 必须为真才能保存任何记录。
    • 由于文章在保存到数据库之前没有 id,因此 article_category_relationships 中的任何 article_id 为空。 因此,只要您需要同时CREATE新文章及其子对象,article.valid? 将始终为 false
    • 总结一下,这里是rails的步骤:
      1. 验证文章本身,成功!(注意:已保存注释)
      2. 为每个 article.articles_category_relationships 验证articles_category_relationship,article_id 未提供,失败!

    你能做什么

    1. 先创建文章
    2. 为这个创建的文章分配参数
    3. 使用参数更新

    【讨论】:

      【解决方案2】:

      尝试使用:

      @a_particular_article.article_category_relationships.build(params[:something])
      

      您可以查看here 了解更多信息,并且可能想查看nested attributesvalidates_associated

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 1970-01-01
        相关资源
        最近更新 更多