Ruby on Rails NoMethodError in Articles#show



我一直收到无方法错误。为什么?我该如何解决这个问题?

文章中的无方法错误#显示 # 的未定义方法"照片">

我在轨道上使用红宝石,我正在尝试使用回形针,以便我可以在我的应用程序上上传照片

我的节目文件的一部分

<%= render @article.photos %>  #source of error
<h3>Add a photo:</h3>
<%= render 'photos/form' %>

"我的照片"控制器

class PhotosController < ApplicationController
#Index action, photos gets listed in the order at which they were created
def index
@photos = Photo.order('created_at')
end
#New action for creating a new photo
def new
@photo = Photo.new
end
#Create action ensures that submitted photo gets created if it meets the requirements
def create
@article = Article.find(params[:article_id])
@photo = @article.photos.create(photo_params)
redirect_to article_path(@article)

end
def destroy
@article = Article.find(params[:article_id])
@photo = @article.photos.find(params[:id])
@photo.destroy
redirect_to article_path(@article)
end
private
#Permitted parameters when creating a photo. This is used for security reasons.
def photo_params
params.require(:photo).permit(:title, :image)
end
end

=========更新 =======

这是我的 文章控制器

class ArticlesController < ApplicationController
def new
@article = Article.new
end
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end

文章模型

class Article < ApplicationRecord
has_many :comments
end

我现在修复了它,但现在我又有另一个无方法错误

#<#的未定义方法"article_photos_path":0x007f17f052d0a0>你的意思是? article_path

<%= form_for([@article, @article.photos.build]) do |f| %> #source of error
<div class="form-group">
<%= f.label :image %>
<%= f.file_field :image, class: 'form-control'%>
</div>
<p>
<%= f.submit 'Upload Photo' %>
</p>
<% end %>
</p>
<% end %>

Being Photo 另一个模型 因此,您需要建立适当的关系:

class Article < ApplicationRecord
has_many :comments
has_many :photos
end
class Photo < ApplicationRecord
belongs_to :article
end

正如我在photo_params中看到的,您没有article_id属性,那么您必须添加它,运行迁移:

$ rails g migration add_article_to_photos article:references
$ rails db:migrate

之后,您应该更新它们:

params.require(:photo).permit(:title, :image, :article_id)

最新更新