我有三个模型:专业、职业、学校。您可以为每个人添加评论。关联如下所示:
Major.rb、School.rb、Career.rb
has_many :reviews, as :reviewable
评论.rb
belongs_to :user
belongs_to :reviewable, polymorphic: true
用户.rb
has_many :评论
我的路线如下所示:
resources :majors, :schools, :careers do
resources :reviews
end
当您转到这样的网址时,我希望能够显示与特定专业相关的所有评论:majorfinder.com/majors/major-name/reviews 但它显示以下错误:
NoMethodError in Reviews#index
Showing /Users/lauraleeflores/Sites/rails/mattan/app/views/reviews/_review.html.erb where line #4 raised:
undefined method `review_path' for #<#<Class:0x007fd788ee3b28>:0x007fd78a9d6930>
Extracted source (around line #4):
1: <% @reviews.each do |review| %>
2: <tr>
3: <td><%= review.review %></td>
4: <td><%= link_to 'Show', polymorphic_path([review.reviewable, review]) %></td>
5:
6: <% if current_user == review.user %>
7: <td><%= link_to 'Edit', edit_major_review_path(review) %></td>
我现在已经解决了这个问题,对于任何有同样问题的人来说,这是如何解决的:
问题出在我的控制器和链接中。
这是我更新的审查控制器:
def index
@reviews = @reviewable.reviews
end
def show
@review = @reviewable.reviews.find(params[:id])
end
def new
@review = @reviewable.reviews.build
@review.user = current_user
end
def edit
@review = @reviewable.reviews.find(params[:id])
raise(ActiveRecord::RecordNotFound, "Access Denied") if @review.user != current_user
end
def create
@review = @reviewable.reviews.build(params[:review])
@review.user = current_user
end
def update
@review = @reviewable.reviews.find(params[:id])
raise(ActiveRecord::RecordNotFound, "Access Denied") if @review.user != current_user
end
def destroy
@review = @reviewable.reviews.find(params[:id])
@review.destroy
raise(ActiveRecord::RecordNotFound, "Access Denied") if @review.user != current_user
end
然后这是我的评论索引页面的一部分:
<% @reviews.each do |review| %>
<tr>
<td><%= review.review %></td>
<td><%= link_to 'Show', major_review_path(@reviewable, review) %></td>
<% if current_user == review.user %>
<td><%= link_to 'Edit', edit_major_review_path(@reviewable, review) %></td>
<td><%= link_to 'Delete', major_review_path(@reviewable, review), method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
<% end %>
<%= link_to 'New Review', new_major_review_path %>
这是我的展示页面的一部分:
<p>
<b>Review:</b>
<%= @review.review %>
</p>
<p>
<b>Review Profile Name:</b>
<%= @review.user.profile_name %>
</p>
<p>
<b>Review User ID:</b>
<%= @review.user %>
</p>
<p>
<b>Current User</b>
<%= current_user %>
</p>
<p>
<b>Major that this review is for:</b>
<%= @review.reviewable %>
</p>
<% if current_user == @review.user %>
<%= link_to 'Edit', edit_major_review_path(@reviewable) %> |
<% end %>
<%= link_to 'Back', major_reviews_path %>
这是我使用 simple_form 的新评论表单:
<%= simple_form_for([@reviewable, @review]) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :review %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
希望对和我有同样情况的人有所帮助!