我正在开发一个 ror 网络,我试图 ajaxing 评论。网络上有带有评论的品牌和产品。我首先尝试 ajaxing 品牌的评论。
品牌型号
class Brand < ActiveRecord::Base
attr_accessible :name
has_many :products, :dependent => :destroy
has_many :comments, :dependent => :destroy
validates :name, :presence => true
end
评论的模型
class Comment < ActiveRecord::Base
attr_accessible :body, :brand_id, :product_id, :user_id
belongs_to :brand
belongs_to :product
validates :brand, :presence => {:unless => :product_id?, :message => "The comment must belongs to a brand or product"}
validates :product, :presence => {:unless => :brand_id?, :message => "The comment must belongs to a brand or product"}
validates :body, :presence => true
end
评论控制器创建
def create
@comment = Comment.new(params[:comment])
@brand = Brand.find(params[:comment][:brand_id])
respond_to do |format|
if @comment.save
@comments = @comment.brand.comments
format.html { redirect_to @brand, notice: 'Comment was successfully created.' }
format.json { render json: @comment, status: :created, location: @comment }
format.js { render @brand}
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
意见/品牌/_comments
<div class="well">
<%= simple_format comments.body %>
<%= link_to 'Edit', edit_comment_path(comments), :class => 'btn btn-mini btn-success' %>
<%= link_to 'Destroy', comment_path(comments), :method => :delete, :data => {:confirm => 'Are you sure?'}, :class => 'btn btn-mini btn-danger' %>
</div>
意见/评论/create.js.rjs
$("#comments").html("<%= escape_javascript(render :partial => "comments", :collections => @comments) %>");
浏览量/品牌/展示
<h2>Comments</h2>
<div id="comments">
<%= render :partial => "comments", :collection => @comments %>
</div>
<p></p>
<div id="comment-form">
<%= form_for @comment, :remote => true do |f| %>
<%= f.hidden_field :brand_id %>
<div class="field">
<%= f.text_area :body, :size => "25x5"%>
</div>
<div class="field">
<%= f.submit 'Enviar comentario', :class => 'btn btn-success' %>
</div>
<% end %>
</div>
但是当我创建一个新产品时,页面被重新加载。真的很谢谢你!