###no method errorになってしまう
環境
cloud9
rails4.2.8
Mqsql2 0.3.18'
ruby 2.5.3
以下の様にPostテーブル(親)とPosttools(子)テーブルでアソシエーションを組んでいる。
class Post < ActiveRecord::Base has_many :posttools, dependent: :destroy accepts_nested_attributes_for :posttools ,allow_destroy: true end class Posttool < ActiveRecord::Base belongs_to :post belongs_to :tool end
###Postインスタンス.Posttoolsインスタンスの時に、配列の要素を消したい・・・ができない
[1] pry(#<PostsController>)> @post => #<Post:0x00000006831548 id: nil, user_id: 1, title: "なんということだ", created_at: nil, updated_at: nil, likes_count: 0, comments_count: 0, youtube: "", series: nil, unread: 0> [2] pry(#<PostsController>)> @post.posttools => [#<Posttool:0x0000000680baa0 id: nil, post_id: nil, tool_id: 1, created_at: nil, updated_at: nil>, #<Posttool:0x00000006808aa8 id: nil, post_id: nil, tool_id: nil, created_at: nil, updated_at: nil>, #<Posttool:0x00000006801f28 id: nil, post_id: nil, tool_id: nil, created_at: nil, updated_at: nil>]
@postの下にPosttoolsのモデルオブジェクトを配列で複数入れて@post.saveでテーブルにレコードを作っています。
この時、tool_idがnilの時は、そのオブジェクト(要素)だけ消したいのですが
(ここで言うと <Posttool:0x00000006808aa8 id: nil, post_id: nil, tool_id: nil, created_at: nil, updated_at: nil>,
<Posttool:0x00000006801f28 id: nil, post_id: nil, tool_id: nil, created_at: nil, updated_at: nil>] この2つ)
[23] pry(#<PostsController>)> @post.posttools.delete_at(1) NoMethodError: undefined method `delete_at' for #<Posttool::ActiveRecord_Associations_CollectionProxy:0x00000005eec7f8> Did you mean? delete_all delete from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.8/lib/active_record/relation/delegation.rb:136:in `method_missing'
no methoderrorになってしまいます。
###どうすればよいのか
そもそも他のcompact!などのメソッドも使用できず、調べて使用できるメソッドを表示したらこんな感じでした。
[14] pry(#<PostsController>)> @post.posttools.methods => [:method_missing, :<<, :==, :empty?, :length, :size, :to_ary, :to_a, :new, :include?, :find, :count, :select, :first, :any?, :take, :replace, :clear, :concat, [15] pry(#<PostsController>)> a = []
ということはこれしか使えない?
delete_atのソースを調べてposttools.rbに書こうともしたけど正直よくわかりませんでした。
どうすればよいでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/08 13:37