私のアプリには関連付けの問題がありますが、修正できません。私のアプリは非常にシンプルです。Articleモデルがあります。各記事にはhas_manyコメントがあり、これらのコメントにはそれぞれhas_many票があり、私の場合は「賛成」です。
私がそれを設計した方法を説明するために、私はコメントの足場を作り、コメントモデルを編集し、ネストされたリソースにルーティングしました。すべてが正常に機能します。ここで、基本的に「賛成」に対して同じプロセスを再度実行し、モデルとルートを再度編集して、これをコメントのネストされたリソース内のネストされたリソースにしました。しかし、これは次の時点で失敗します。
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 %>
この場合、「賛成票」が未定義であるのはなぜですか。
<%= 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
これだけのコードでごめんなさい..、私のarticles_controller :(抜粋)
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
そんなに多くのコードでごめんなさい。誰かがこれに答えるなら、彼らはとても素晴らしいでしょう!前もって感謝します!