Kev*_*vin 2 ruby-on-rails ruby-on-rails-3
这就是我的模型为简单博客定义的方式
def User
has_many :comments, :dependent => :destroy
has_many :posts
end
def Post
belongs_to :user
has_many :comments
end
def Comment
belongs_to :user
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
在我的Post Controller中,我有这个代码,以便我可以在视图中创建一个注释
def show
@post = Post.find(params[:id])
@comment = Comment.new
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
Run Code Online (Sandbox Code Playgroud)
然后在我的评论#create中我有这个
def create
@comment = current_user.comments.create(params[:comment])
if @comment.save
redirect_to home_show_path
else
render 'new'
end
end
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能让我的评论模型能够收到post_id?我已经在我的Post show视图中做了这个作为修复,但还有另一种更好的方法吗?
<%= f.hidden_field :post_id, :value => @post.id %>
Run Code Online (Sandbox Code Playgroud)
post_id在表单中设置隐藏字段并没有什么不妥- 但是它确实意味着人们可能会将他们的评论与任何随机帖子相关联.
更好的方法可能是使用嵌套资源来发布帖子的评论.为此,请在routes.rb文件中设置以下内容:
resources :posts, :shallow => true do
resources :comments
end
Run Code Online (Sandbox Code Playgroud)
然后你的表单应如下所示:
<%= form_for @comment, :url => post_comments_path(@post) do %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
这意味着表单POST到路径/post/[:post_id]/comments- 这意味着post_id可以作为参数用于控制器:
def create
@comment = current_user.comments.new(params[:comment])
@comment.post = Post.find(params[:post_id])
if @comment.save
...
end
end
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以使用post id对Post进行选择,如果找不到Post,则会引发错误.
也许值得稍微重写那个控制器方法,以便Post.find首先出现:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
@comment.user = current_user
if @comment.save
...
end
end
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.