Tôi làm một blog đơn giản trên đường ray. Tôi có mô hình Đăng và mô hình Nhận xét. Khi bạn tạo nhận xét, nếu nhận xét không hợp lệ, tôi muốn hiển thị lỗi. Tôi phải làm như thế nào?Vượt qua một biến từ bộ điều khiển để xem
mô hình mới gởi:
#/models/post.rb
class Post < ActiveRecord::Base
has_many :comments
validates :title, :content, :presence => true
end
mô hình Comment:
#/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates :name, :comment, :presence => true
end
Comments khiển
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
end
Xem cho hình thức bình luận:
/views/comments/_form.html .erb
<%= form_for([@post, @post.comments.build]) do |f| %>
<% if @comment.errors.any? %>
error!
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
/views/posts/show.html.erb
<%= render 'comments/form' %>
Làm thế nào để vượt qua @comment từ CommentController điều khiển để xem /post/show.html.erb?
Xin cảm ơn trước.
Không '@post.comments', nơi bạn có tất cả nhận xét của bài đăng, bao gồm cả nhận xét mới được tạo, đủ? – clyfe