コメント機能を実装したいと思っています。
各投稿欄にコメントフォームを設置し、そこからコメントすることで該当する投稿にコメントがされるというものです。
例)
投稿1
コメント投稿数 (0)
[コメントフォーム]
投稿2
コメント投稿数 (1)
[コメントフォーム] ←このフォームで送信することで、投稿2にコメントするようなシステム
投稿3
コメント投稿数 (0)
[コメントフォーム]
投稿(Twiモデル)との関連付けがうまくいかず悩んでいます。
(具体的には、外部キーのtwi_idをどのように格納すれば良いか分かりません・・・)
解決策、改善案お持ちの方、ご助力をお願いいたします。
各コード情報は以下となります。
モデルのアソシエーション
User.rb has_many :twis belongs_to :comment Twi.rb has_many :comments belongs_to :user Comment.rb belongs_to :user belongs_to :twi
投稿一覧ページ(Twis/index)
<% @twis.each do |t| %> <%= t.user.name %> <%= t.msg %> <%= t.comment.count %> <%= render 'comments/form', comment: @comment, id:t.id %> <% end %>
TwiController (indexアクション)
def index users = User.where 'account_id == ?', current_account.id if users[0] == nil then user = User.new user.account_id = current_account.id user.save users = User.where 'account_id == ?', current_account.id end @user = users[0] @twis = Twi.page(params[:page]).order(created_at: :desc) @comment = Comment.new @comment.user_id = @user.id end
CommentController
def new users = User.where 'account_id == ?', current_account.id if users[0] == nil then user = User.new user.account_id = current_account.id user.save users = User.where 'account_id == ?', current_account.id end @user = users[0] @comment = Comment.new @comment.user_id = @user.id end def create @comment = Comment.new(comment_params) respond_to do |format| if @comment.save format.html { redirect_to '/twis', notice: 'Comment was successfully created.' } format.json { render :show, status: :created, location: @comment } else format.html { render :new } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end def comment_params params.require(:comment).permit(:body, :twi_id, :user_id) end
投稿フォーム(comments/_form.html.erb)
<%= form_with(model: comment, local: true) do |form| %> <% if comment.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:</h2> <ul> <% comment.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.text_area :body, id: :comment_body %> <%= form.submit '送信' %> <%= form.hidden_field :twi_id, id: :comment_twi_id %> <%= form.hidden_field :user_id, id: :comment_user_id %> </div> <% end %>
投稿一覧ページ(Twis/index)の変数tをフォームと関連付けられれば早いと思うのですが・・・
何卒よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/02/25 04:54
2018/02/25 09:44
退会済みユーザー
2018/03/01 02:56
2018/03/01 23:08
2018/03/03 22:29