質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

1583閲覧

polymorphicのbelongs_to(commentable)のbooleanを変更したい

hns

総合スコア10

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2017/06/27 14:04

編集2017/06/28 01:56

belongs_to :commentable のモデル(Article)のbooleanをモデルファイルを通して変更したいのですが詰まっています。
before_save でやろうと思っていたのですが変更してくれないです。

comment.rb

# == Schema Information # # Table name: comments # # id :integer not null, primary key # text :text # user_id :integer not null # commentable_id :integer # commentable_type :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_comments_on_commentable_id_and_commentable_type (commentable_id,commentable_type) # index_comments_on_user_id (user_id) # class Comment < ApplicationRecord belongs_to :user, optional: true belongs_to :commentable, polymorphic: true validates :text, presence: true before_create :increment_counter before_destroy :decrement_counter # 問題の箇所 # before_save -> after_save # after_save でもダメでした after_save do if self.commentable.comments_count == 0 self.commentable.any_response = false else self.commentable.any_response = true end true end private # Instead of counter_cache def increment_counter self.commentable_type.constantize.increment_counter("comments_count", self.commentable_id) end # Instead of counter_cache def decrement_counter self.commentable_type.constantize.decrement_counter("comments_count", self.commentable_id) end end

article.rb

# == Schema Information # # Table name: articles # # id :integer not null, primary key # text :string default(""), not null # any_response :boolean default(FALSE), not null # comments_count :integer default(0) # article_category_id :integer not null # user_id :integer not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_articles_on_article_category_id (article_category_id) # index_articles_on_user_id (user_id) # class Article < ApplicationRecord validates :text, presence: true belongs_to :user, counter_cache: true belongs_to :article_category, counter_cache: true has_many :comments, as: :commentable before_save :add_user_id private def add_user_id self.user_id = self.article_category.user_id end end

indexのページで、ajaxを使ってarticle#showを呼び出し
そこに、article.comments.each でコメント一覧と
article.comments.build でフォームを出してます。

= simple_form_for(article.comments.build, url: article_comments_path(article), remote: true) do |f| .row = f.input :text .row = f.button :submit

comments_controller.rb

class Users::Public::CommentsController < AuthenticateUserController before_action :load_commentable respond_to :html, :js def create @comment = @commentable.comments.build(comment_params) @comment.user_id = current_user.id @comment.save end private def load_commentable resource, id = request.path.split('/')[1, 2] @commentable = resource.singularize.classify.constantize.find(id) end def comment_params params.require(:comment).permit(:text, :user_id) end end
$ > rails console $ > @article = Article.first #<Article:0x007f9a0a237cc8> { :id => 1, :text => "Nemo odit consectetur impedit.", :any_response => false, :comments_count => 0, :thumbs_count => 0, :article_category_id => 1, :user_id => 1 } $ > @article.comments.create(user_id: 1, text: 'hello') #<Comment:0x007f9a0b0d4c90> { :id => 1, :text => "hello", :user_id => 1, :commentable_id => 1, :commentable_type => "Article" } $ > @article.any_response false $ > Comment.last #<Comment:0x007f9a0dd4cbb0> { :id => 1, :text => "hello", :user_id => 1, :commentable_id => 1, :commentable_type => "Article" }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

多分5、6時間ハマってました。。。。。。
stackoverflow見てたら、応用できそうなのを見つけました。

after_save callback in post model is being triggered when I create a vote?

ただ単に、updateすればよかったみたいです

comment.rb

1 2 after_save :response_confirmed 3 4 private 5 6 def response_confirmed 7 self.commentable.update(any_response: false) if self.commentable.comments_count == 0 8 self.commentable.update(any_response: true) 9 end

これで一応動きます、一応

一応updateしときます 2017/07/08

こうですね。

before_create :response_confirmed_true before_destroy :response_confirmed_false private def response_confirmed_true self.thumbable.update_column(:any_responsed, true) end def response_confirmed_false self.thumbable.update_column(:any_responsed, false) if self.thumbable.comments_count == 0 end

投稿2017/06/28 13:18

編集2017/07/08 04:36
hns

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

moke

2017/06/29 00:21

なるほど返信が遅くなってしまってすみません。 勉強になりました。
guest

0

コメントのsave前にArticleが存在しないのでは?
comment_controllers.rb等を見ないとなんとも言えませんが
nested_attributes_forを使っている場合
before_saveをafter_saveに変えればArticleが存在しているので
commentからself.commentable.comments_count等でアクセスできるようになると思います。

そうでない場合、どのように保存しているかのロジックを全て晒してください。
この続きに回答します。

投稿2017/06/27 15:31

moke

総合スコア2241

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hns

2017/06/28 01:41

after_saveに変更しても self.commentable.any_response は trueにできませんでした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問