【问题标题】:Saving One-To-Many Model With Nested Attributes保存具有嵌套属性的一对多模型
【发布时间】:2023-03-14 00:16:02
【问题描述】:

使用 Rails 4 和 Ruby 2.1。

假设我有两个模型,Team 和 Player。它们看起来像这样:

team.rb:

# == Schema Information
#
# Table name: teams
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Team < ActiveRecord::Base
    has_many :players

    accepts_nested_attributes_for :players
end

播放器.rb:

# == Schema Information
#
# Table name: players
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  team_id    :integer
#  created_at :datetime
#  updated_at :datetime
#

class Player < ActiveRecord::Base
    belongs_to :team
end

超级简单。我可以毫不费力地做到以下几点:

> params = { team: {
>       name: "Foo", players_attributes: [
>         {name: "Bar"}
>       ]
>     }}
> team = Team.new(params[:team]) # => #<Team id: nil, name: "Foo", created_at: nil, updated_at: nil> 
> team.save # => true
> team.players.first.name # => "Bar"

好的。现在假设我更新了 Player 模型,这样就无法在没有属于 Team 的情况下创建 Player:

播放器.rb:

# == Schema Information
#
# Table name: players
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  team_id    :integer
#  created_at :datetime
#  updated_at :datetime
#

class Player < ActiveRecord::Base
    belongs_to :team

    validates_presence_of :team
end

现在当我尝试同样的事情时:

> params = { team: {
>       name: "Foo", players_attributes: [
>         {name: "Bar"}
>       ]
>     }}
> team = Team.new(params[:team]) # => #<Team id: nil, name: "Foo", created_at: nil, updated_at: nil> 
> team.save # => false
> team.errors # => #<ActiveModel::Errors:0x00000002bd13f0 @base=#<Team id: nil, name: "Foo", created_at: nil, updated_at: nil>, @messages={:"players.team"=>["can't be blank"]}>

在没有玩家要求的团队的情况下,team_id 显然是使用嵌套属性设置的。但是,只要我需要它,验证就会在它有机会被设置之前破坏。我做错了吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    替换

    class Team < ActiveRecord::Base
      has_many :players
      accepts_nested_attributes_for :players
    end
    
    class Player < ActiveRecord::Base
      belongs_to :team
      validates_presence_of :team
    end
    

    class Team < ActiveRecord::Base
      has_many :players, inverse_of: :team
      accepts_nested_attributes_for :players
    end
    
    class Player < ActiveRecord::Base
      belongs_to :team, inverse_of: :players
      validates_presence_of :team
    end
    

    在关联中添加inverse_of 选项。

    【讨论】:

    • 嗯!我以前从未使用过它,它解决了这个问题。谢谢@Kirti!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多