1

Rails 3 で基本的な「ブログのような」アプリを書こうとしているのですが、関連付けに行き詰まっています。create メソッドで post_id と user_id をコメント テーブルに保存する必要があります (これは、ユーザーが書いたすべてのコメントを取得して表示するために必要です)。

このアプリには、ユーザー (認証 - デバイス)、投稿 (ユーザーによって投稿されましたが、私の場合は重要かどうかはわかりません)、およびコメント (ユーザーによって投稿された投稿について) があります。

コメント テーブルには、post_id、body、および 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

投稿表示ビューに表示されるコメント投稿フォーム: (posts/show.html.erb)

<% form_for [@post, Comment.new] do |f| %>
  <%= f.label :body %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

最後に、コメント コントローラーの create メソッド:

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))

しかし、それは機能しません.. user_id と post_id を保存するメソッドを作成するにはどうすればよいですか? コメント投稿フォームにも変更を加える必要がありましたか ( <% form_for [@post, @user, Comment.new] do |f| %> のようなものですか?)

ありがとうございました!

4

1 に答える 1

4

非常によく似たものを設定するために、次のフォームを使用しました。

<%= 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

終わり

うまくいけば、関連付けが適切に構築されるはずです。余談ですが、ルートの :users の下にコメントをネストするということですか? プロフィール ページにすべてのユーザーのコメントを表示したい場合は、次のようにします。

<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>

その一部が役立つことを願っています!

于 2010-09-17T08:05:58.270 に答える