Rails Associations(belongs_to、has_many)は、作成方法(ユーザー、投稿、コメント)を使用してテーブルに2つのIDを保存できません
-
03-10-2019 - |
質問
Rails 3に基本的な「ブログのような」アプリを作成しようとしているので、協会にこだわっています。 CREATEメソッドは、コメントテーブルにPOST_IDとuser_idを保存する必要があります(ユーザーが書いたすべてのコメントを表示するためにすべてのコメントを取得するために必要です)
アプリにはユーザー(認証 - devise)、投稿(ユーザーによる投稿 - しかし、私の場合は重要であるかどうかはわかりません)、コメント(投稿、ユーザーが投稿)。
コメントテーブルには、post_id、ボディ、およびuser_idがあります
協会:
has_many :comments (In the Post model)
belongs_to :post (In the Comment model)
belongs_to :user (In the Comment model)
has_many :comments (In the User model)
ルート:
resources :posts do
resources :comments
end
resources :users do
resources :comments
end
投稿に表示されるコメント投稿フォームshow :( posts/show.html.erb)
<% form_for [@post, Comment.new] do |f| %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
そして最後に、コメントコントローラーの作成メソッド:
A.)これを書くと、post_idがデータベースに記述されています
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
redirect_to @post
end
B.)私がこれを書いた場合、user_idは書かれています...
def create
@user = current_user
@comment = @user.comments.create!(params[:comment])
redirect_to @post
end
私は試した:
@comment = @post.comments.create!(params[:comment].merge(:user => current_user))
しかし、それはうまくいきません..ユーザー_IDとpost_idを保存する方法を書くにはどうすればよいですか?また、コメント投稿フォームで変更を行う必要がありましたか(<%form_for [@post、@user、new] do | f |%>?)
ありがとうございました!
解決
非常によく似たものをセットアップするために、次のフォームを使用しました。
<%= form_for [:place, @comment] do |f| %>
#form fields here
<%= end %>
次に、コメントコントローラーで:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user = User.find(current_user.id)
respond_to do |format|
if @comment.save
format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
else
format.html { render :action => "new" }
end
end
終わり
それはうまくいけば協会を適切に構築するはずです!余談ですが、コメントがネストされることを意味しますか:あなたのルートのユーザー?プロフィールページにすべてのユーザーのコメントを表示したい場合は、次のようなことができます。
<p>
<b>Comments</b>
<% if @user.comments.empty? %>
No comments to display yet...
<% else %>
<% @user.comments.each do |comment| %>
<p>
<%= link_to "#{comment.post.title}", post_path(comment.post_id) %>, <%= comment.created_at %>
<%= simple_format comment.content %>
</p>
<% end %>
<% end %>
</p>
それのいくつかが役立つことを願っています!