0

2 つの単純なモデルがあります。

class Idea << ActiveRecord::Base
  has_many :tasks

  # for nesting....
  accepts_nested_attributes_for for :tasks
  attribute_accessible :tasks_attributes
end

class Task << ActiveRecord::Base
  belongs_to :idea
  validates_presence_of :idea # this line is causing pain
end

次の JSON を送信して、IdeasController を作成します。

{
    "description":"Test test test",
    "tasks":[{"description":"test test test"}]
}

...そして、検証エラーが返されます。検証を削除するとすぐに、すべてがうまくいきます!

助言がありますか?

4

1 に答える 1

1

逆関連付けを定義すると、次のことが役立ちます。

class Idea << ActiveRecord::Base
  has_many :tasks, inverse_of: :idea # here...
  accepts_nested_attributes_for :tasks
  attribute_accessible :tasks_attributes
end

class Task << ActiveRecord::Base
  belongs_to :idea, inverse_of: :tasks # ... and here
  validates_presence_of :idea 
end

検証が失敗する理由は、この修正前の関連付けが単方向であるためです。タスクの に到達しようとすると、タスクideaのアイデアからタスクに到達するために使用される関連付けプロキシを使用する代わりに、アイデアの存在 (申し訳ありませんが、説明するのは少し難しいです)。

また、必ずvalidates_presence_of :ideaand NOTを使用してvalidates_presence_of :idea_idください。tasks_attributesさらに、 だけではなく jsonで使用する必要がありますtasks

于 2013-04-11T07:06:06.357 に答える