前提・実現したいこと
現在、ツイッターに似ているアプリを作成していて、
userのプロフィール画像はアップロードできたのですが、投稿の際に画像をアップロードすることができません。
画像投稿の際はもう一つuploaderファイルを作成する必要があるのでしょうか?
発生している問題・エラーメッセージ
エラーメッセージ NoMethodError in Tweets#create undefined method `image' for nil:NilClass .header__right__triangle = link_to "投稿", new_tweet_path, class: "header-list top-hover" = image_tag @user.image.url, class: "hesder-userimage" = link_to current_user.name, user_path(current_user.id), class: "header-username" -else = link_to "sign_up", new_user_registration_path, class: "header-list top-hover"
該当のソースコード
tweets_controller.rb
class TweetsController < ApplicationController def new @tweet = Tweet.new @user = User.find(current_user.id) end def create @tweet = Tweet.new if @tweet.save(tweet_params) redirect_to (root_path) else render action: "new" end end private def tweet_params params.require(:tweet).permit(:text, :picture) end end ### 試したこと ここに問題に対して試したことを記載してください。 ### 補足情報(FW/ツールのバージョンなど) ここにより詳細な情報を記載してください。
new.html.haml
.tweets-wrpper = render "homes/header" .tweets-header 投稿フォーム .tweets-formbox = form_with model: @tweet, method: :post, local: true do |f| %p.tweets-text 写真 = f.file_field :picture, type: 'file', autocomplete: "picture" %p.tweets-text 投稿内容 = f.text_area :text, class: "tweets-area" = f.submit "投稿", class: "tweets-btn"
tweet.rb
class Tweet < ApplicationRecord belongs_to :user mount_uploader :picture, PictureUploader end
user.rb
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable mount_uploader :image, ImageUploader has_many :tweets end
試したこと
userのプロフィール画像で使用したimage_uploaderとは別に
画像投稿の際に使用するpicture_uploaderを作成した。
補足情報
tweetモデルの画像の保存先はpictureカラムで設定しています。
画像投稿の際、以下のgemを使用しています。
gem 'carrierwave'
gem 'mini_magick'
あなたの回答
tips
プレビュー