小编Fin*_*inn的帖子

是否包含相反的内容?对于Ruby Arrays?

我的代码中有以下逻辑:

if !@players.include?(p.name)
  ...
end
Run Code Online (Sandbox Code Playgroud)

@players是一个数组.是否有方法可以避免!

理想情况下,此代码段将是:

if @players.does_not_include?(p.name)
  ...
end
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails

175
推荐指数
7
解决办法
11万
查看次数

在Rails中访问未保存的父母和孩子的祖父母

我有一个表格可以将一个Parent和多个Child对象保存在一起.在初始化Child对象期间,它需要访问Grandparent.这是模型的样子:

class Grandparent
  has_many :parents, inverse_of: :grandparent
end

class Parent
  belongs_to :grandparent, inverse_of: :parents
  has_many :children, inverse_of: :parent
  accepts_nested_attributes_for :children
end

class Child
  belongs_to :parent
  delegate :grandparent, to: :parent

  # Test code
  after_initialize do
    raise 'NoParentError' unless parent.present?
    raise 'NoGrandparentError' unless grandparent.present? # Errors here!
    puts 'All good!'
  end
end
Run Code Online (Sandbox Code Playgroud)

请记住,表单用于同时保存新父项和多个子项,但我正在尝试访问祖父项对象中的信息.我读到inverse_of选项应该已经完成​​了这个伎俩,但child.grandparent仍然nil不幸.

这是实际导致失败的控制器部分:

@parent = @grandparent.parents.build(parent_params)
# prior to saving @parent
Run Code Online (Sandbox Code Playgroud)

由于某种原因,父母不知道祖父母是谁.

更新

看起来我可以通过以下代码解决该错误:

@parent = Parent.new(parent_params.merge(grandparent: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails associations nested-forms

5
推荐指数
1
解决办法
367
查看次数

标签 统计

ruby-on-rails ×2

associations ×1

nested-forms ×1

ruby ×1