我试图在“创建”下将控制器内的这两个代码合并为一个
class PostcommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Postcomment.new(params[:postcomment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
redirect_to(:back)
else
render partial: 'shared/_postcomment_form', locals: { micropost: @micropost }
end
end
def create2
@discussion = Discussion.find(params[:discussion_id])
@comment = Postcomment.new(params[:postcomment])
@comment.discussion = @discussion
@comment.user = current_user
if @comment.save
redirect_to(:back)
else
render partial: 'shared/_postcomment_form', locals: { discussion: @discussion }
end
end
end
我在“创建”下尝试了这两个代码,它们都可以工作。我有两个模型将postcomment 关联到:micropost 和讨论。我想应用正确的“创建”,具体取决于它是微博还是讨论。
这是我在讨论中使用的内容
<%= form_for([@discussion, @comment]) do |f| %>
<%= f.text_field :comment_content %>
<button class="btn" type="submit">
Comment
</button>
<% end %>