为我的模型rails3添加星级

时间:2012-06-07 17:41:31

标签: ruby-on-rails

我有一个名为老师的模型,我想将评分添加到(5星)。目前,我通过在我的教师资源中添加评级嵌套路由(资源评级)来实现此目的。然后我创建了一个模型:评级为(id,user_id,teacher_id,rating,...)。然后我创建了一个带有隐藏字段的表单,其中一个名为 stars 。当用户点击星号时,我使用jQuery发送AJAX请求来创建/更新该用户和教师的评级。

我的困惑是:我在页面上有两个单独的表单。我有一份撰写评论者评论的表格。此表单有两个字段:标题,注释(和提交)。然后我有隐藏字段的评级表。这是正确的方式去做这样的事情吗?在我看来,我确实应该在主要评论表格中嵌入评级模型字段。

任何帮助高度赞赏。谢谢。

[编辑]

我已更新了我的应用程序,因此用户现在不会评估教师对象,而是对教师

评估评论 >

我的设置是这样的:

路由

resources :comments as :teacher_comments do  
 resource :rating  
end  

模型

注释

has_one :rating  
attr_accessible :body, :rating_attributes  
accepts_nested_attributes_for :rating  

等级

belongs_to :comment  
attr_accessible :stars, :user_id, :teacher_id, :comment_id  

视图

<%= form_for( @comment, :remote => true, :url => teacher_comments_path ) do |tc| %>
  <%= tc.text_area :body, :maxlength => 450  %>
  <%= tc.fields_for :rating do |builder| %>
    <%= builder.text_field :stars  %>
  <% end %>
<% end %>

我没有看到明星的text_field。它只是没有出现。有没有我错过的东西?

1 个答案:

答案 0 :(得分:1)

事实上,将所有这些字段放在一个单一的形式(通常有利于用户体验)通常会更好。

修改

您可以使用方法accepts_nested_attributes_for(如下面评论中所建议的那样)。将以下内容放在您的父模型(教师)中;那么你应该能够创建一个表单来处理两个模型的输入:

在模型中:

class Comment < ActiveRecord::Base
  has_one :rating
  accepts_nested_attributes_for :rating
end

在控制器中:

def new
  @comment = Comment.new
  @comment.rating = Rating.new
end

Ryan Bates在这里详细介绍了这些概念的使用情况:Nested Model Form。我推荐给想要了解更多细节的用户。

<强>原始

这意味着您需要将表单指向可以处理这两种输入的操作。如果您愿意,您仍然可以使用form_for,但请指定默认操作以外的操作(或更改teacher_controller.rb文件中默认操作中的代码):

<%= form_for @teacher, :url => {:action => 'create_and_rate'} do |f| %>

由于评级是与教师(我们刚刚创建的表单)不同的模型,因此您需要为评级字段使用通用_tag表单助手。

<%= text_field_tag :rating, :name %> # rating's fields should use the generic form helper
<%= f.text_field :name %> # teacher's fields can use the specific form helper

由于您指向的是非RESTful操作,请将其添加到路径文件中。

resources :teacher do
  :collection do
    post 'create_and_rate' # this will match /teachers/create_and_rate to TeachersController#create_and_rate
  end
end