【发布时间】:2012-05-28 22:49:05
【问题描述】:
在我的应用中存在关联问题,我无法解决。
我的应用很简单:有一个文章模型;每篇文章都有_many cmets,每个cmets都有_many票,在我的例子中是'upvotes'。
为了解释我的设计方式,我做了一个 cmets 脚手架,编辑了评论模型和路由到嵌套资源,一切正常。现在,我基本上对“upvotes”再次执行了相同的过程,并再次编辑了模型和路线,以使其成为评论嵌套资源中的嵌套资源。但这在以下几点失败了:
NoMethodError in Articles#show
Showing .../app/views/upvotes/_form.html.erb where line #1 raised:
undefined method `upvotes' for nil:NilClass
我的 _form.html.erb 文件如下所示:
<%= form_for([@comment, @comment.upvotes.build]) do |f| %>
<%= f.hidden_field "comment_id", :value => :comment_id %>
<%= image_submit_tag "buttons/upvote.png" %>
<% end %>
为什么在这种情况下'upvotes'未定义,而在这里:
<%= form_for([@article, @article.comments.build]) do |form| %>
rest of code
一切正常吗?我复制了相同的机制,但使用 @comment.upvotes 它不起作用。
我的upvotes_controller:
class UpvotesController < ApplicationController
def new
@upvote = Upvote.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @upvote }
end
end
def create
@article = Article.find(params[:id])
@comment = @article.comments.find(params[:id])
@upvote = @comment.upvotes.build(params[:upvote])
respond_to do |format|
if @upvote.save
format.html { redirect_to(@article, :notice => 'Voted successfully.') }
format.xml { render :xml => @article, :status => :created, :location => @article }
else
format.html { redirect_to(@article, :notice =>
'Vote failed.')}
format.xml { render :xml => @upvote.errors, :status => :unprocessable_entity }
end
end
end
end
我很抱歉这么多代码..,我的文章控制器:(摘录)
def show
@upvote = Upvote.new(params[:vote])
@article = Article.find(params[:id])
@comments = @article.comments.paginate(page: params[:page])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @article }
end
end
还有我的 3 个模型:
class Article < ActiveRecord::Base
attr_accessible :body, :title
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content
belongs_to :user
belongs_to :article
has_many :upvotes
end
class Upvote < ActiveRecord::Base
attr_accessible :article_id, :comment_id, :user_id
belongs_to :comment, counter_cache: true
end
支持迁移文件:
class CreateUpvotes < ActiveRecord::Migration
def change
create_table :upvotes do |t|
t.integer :comment_id
t.integer :user_id
t.timestamps
end
end
end
我的路线:
resources :articles do
resources :comments, only: [:create, :destroy] do
resources :upvotes, only: [:new, :create]
end
end
抱歉,有这么多代码。如果有人能回答这个问题,他们会非常棒! 提前谢谢!
【问题讨论】:
标签: ruby-on-rails-3 build resources nested associations