2012-01-15 35 views
9

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.

+0

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

Trả lời

5

Đặt render "posts/show" thay vì redirect_to post_path(@post) trong CommentsController của bạn.

+0

thật đơn giản! Cảm ơn. – Mike

+0

Bạn hoan nghênh. Ở đây tôi đã chỉ xem xét vấn đề của bạn không thể vượt qua biến thể hiện của một bộ điều khiển để xem. Hãy xem câu trả lời của Vapire, bạn chắc chắn cần khai báo tài nguyên lồng nhau cho mối quan hệ Post-Comments. – shime

+0

bạn có trong mind.rb? tài nguyên: bài đăng làm tài nguyên: bình luận kết thúc. – Mike

2

Và/Hoặc hãy xem Ryan Bates Screencasts về mô hình lồng nhau và các nguồn lực:

Họ Rails 2 nhưng để có được một ý tưởng làm thế nào nó hoạt động nó ok.

lẽ cũng thú vị dành cho bạn:

1

bạn không nên chuyển hướng đến post_path(@post)nếu nhận xét là không hợp lệ.

class CommentsController < ApplicationController 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(params[:comment]) 

    if @comment.save 
     redirect_to post_path(@post), notice: 'Comment was successfully created.' 
    else 
     render action: "posts/show", error: 'The comment you typed was invalid.' 
    end 
    end 
end 

và thay đổi dòng hình thức đầu tiên trong /views/comments/_form.html.erb từ:

<%= form_for([@post, @post.comments.build]) do |f| %> 

tới:

<%= form_for([@post, (@comment || @post.comments.build)]) do |f| %> 

sau đó bạn sẽ thấy thông báo lỗi khi nó không thành công để tiết kiệm.

Các vấn đề liên quan