我一直没有遇到方法错误。为什么?我该如何解决这个问题?
文章中的NoMethodError#show ## p>的未定义方法`photo'
我在铁轨上使用红宝石而我正在尝试使用回形针,以便我可以在我的应用上传照片
我的节目文件的一部分
<%= 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
我现在修好了,但现在又有了一个没有方法错误
#&lt;#:0x007f17f052d0a0&gt;的未定义方法`article_photos_path' 你的意思是? 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 %>
答案 0 :(得分:1)
成为照片的另一个模特,你需要建立正确的关系:
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)