2013-03-22 46 views
0

我有两个模型与相应的控制器和视图:ProfileComment在一个视图中显示来自两个模型的数据

我的应用程序的整个视图(整个网页)在Profileshow.html.erb。在此页面上,用户应该能够创建评论,其中belongs_to a Profile

无需导航到标准/comments/new页面即可完成此操作?

编辑: 继轨指南后,我实现:

<%= simple_form_for([@profile, @profile.comment.build], html: {class: "form-inline"}) do |f| %> 
    <%= f.error_notification %> 

    <%= f.input :description, label: false, placeholder: 'Create an comment', input_html: { class: "span4" } %> 
    <%= f.submit 'Submit', class: 'btn btn-small'%> 

<% end %> 

CommentController

def create 
    @profile = profile.find(params[:profile_id]) 
    @comment = @profile.comments.create(params[:comment]) 
    redirect_to profile_path(@profile) 

而且我得到这个错误:

undefined method `comment' for #<Profile: 

固定:在构建声明,需要的意见是多

@profile.comments.build 
+1

看看这个:http://guides.rubyonrails.org/getting_started.html#generating-a-controller – siekfried 2013-03-22 15:29:47

+0

请参阅上面的错误 – mnort9 2013-03-22 16:26:22

+0

你在表单声明中忘记了's'注释:'<% = simple_form_for([@ profile,@ profile.comments.build]' – siekfried 2013-03-22 19:09:51

回答

1

所有你需要做的就是添加评论表单代码到配置文件#表演。然后在profile_controller的表演动作做这样的事情:

def show 
@comment = Comment.new 
end 

而且在评论控制器添加:

def create 
@comment = Comment.create(params[:comment]) 
end 
+0

我相信你想说的第一种方法是在新的动作中,而不是show动作。 – GKnight 2015-10-06 19:27:42

0

你可能会考虑保存表单和更新使用AJAX调用,并可能像Knockout页面。因此,在profiles/show.html.erb中,制作一个常规(单独)表单来发布评论。使用jQuery或类似的东西通过AJAX将表单发布到/ comments,所以它会在您的评论控制器中执行创建操作。让该控制器返回一个JSON响应,该响应既可以是保存的注释,也可以是类似于{:fieldname =>'too long'}的错误消息的散列。

在客户端上,解析json响应并显示保存的注释,或者显示错误消息,解释为什么无法保存。你可以在普通的jQuery中完成所有这些工作,但添加Knockout之类的东西会使它更简单一些。

相关问题