現在Facebookのような機能をRailsで作成しています。
ユーザは複数の記事と複数のコメントを持ち、
複数の記事は一人のユーザに帰属し、コメントも1つの記事に帰属するという関係です。
ユーザモデル class User < ActiveRecord::Base has_one :member has_many :microposts has_many :comments has_secure_password accepts_nested_attributes_for :member end 記事モデル class Micropost < ActiveRecord::Base belongs_to :user has_many :comments end コメントモデル class Comment < ActiveRecord::Base belongs_to :micropost belongs_to :user end
ですが、
ユーザーコントローラー内で、
@micropost = Micropost.find(params[:micopost_id])を
行うと、
ActiveRecord::RecordNotFound: Couldn't find Micropost with 'id'=
というエラーが発生してしまいます。
そのため、
ユーザと記事に紐付いたコメントが作成できません。
ユーザーコントローラー内で、
binding.pry
を行い、
current_user.micropostsを行ってみると、
このように、
idはすべて表示されていました。
https://gyazo.com/360484d281f5871cd2b0c0215ec53dee
ですが、
上記エラーが出る理由がわかりません。
お手数おかけしますが、
アドバイス宜しくお願いします。
記事とコメントは、
views/users/showで表示させる予定です。
*current_userはログイン中のユーザを表しています。
ユーザコントローラ class UsersController < ApplicationController def show @user = User.find(params[:id]) @micropost = Micropost.find(params[:micopost_id]) @microposts = @user.microposts @microposts.each do |micropost| @comment= micropost.comments.build @comment.user = current_user end end end 記事コントローラー class MicropostsController < ApplicationController before_action :logged_in_user , only: [:create] def create @micropost = current_user.microposts.build(micropost_params) @user = @micropost.user if @micropost.save flash[:success] = "記事を投稿しました。" redirect_to root_path else render 'static_pages/home' end end def destroy @micropost = current_user.microposts.find_by(id: params[:id] ) return redirect_to root_url if @micropost.nil? @micropost.destroy flash[:success] = "削除しました。" redirect_to request.referrer || root_url end private def micropost_params params.require(:micropost).permit(:id,:content) end end コメントコントローラ class CommentsController < ApplicationController def create @microposts = current_user.microposts @comment = Comment.new(comment_params) @microposts.each do |micropost| @comment.micropost = micropost end @comment.user = current_user if @comment.save flash[:success] = "コメントしました。" redirect_to root_path else render 'static_pages/home' end end end
show.html.er <%= @user.first_kanji%> <%= link_to '基本情報編集' ,edit_user_path(@user) %> <% if @user.microposts.any? %> <%= render @microposts %> <% end %> _micropost.html.erb <p><%= micropost.user.first_kanji %> <%= micropost.user.last_kanji %>さん<br /> <%= micropost.content %> <%= render @comment %> <%- if current_user == micropost.user %> <%= link_to "削除", micropost , method: :delete , data:{confirm: "削除してよろしいですか?"} %> <% end %> comment.html.erb <%= comment.content %> <%= form_for(@comment) do |f| %> <%= f.text_field :content %> <%= f.submit '投稿' %> <% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/18 12:14