railsでツイッター系のサイトの開発をしているのですが、画像を投稿すると他の全ての投稿にも新しい画像が反映されてしまいます。
どこかで間違えがあると思いますので教えていただければ幸いです。
class UsersController < ApplicationController def index @users = User.all end def show @user = User.find_by(id: params[:id]) end def new @user = User.new end def create @user = User.new( name: params[:name], email: params[:email], content: params[:content], image_name: "noimage.jpg" ) if params[:image] @user.image_name = "#{@user.id}.jpg" image = params[:image] File.binwrite("public/user_images/#{@user.image_name}", image.read) end if @user.save flash[:notice] = "ユーザー登録が完了しました" redirect_to("/users/#{@user.id}") else render("users/new") end end def edit @user = User.find_by(id: params[:id]) end def update @user = User.find_by(id: params[:id]) @user.name = params[:name] @user.email = params[:email] @user.content = params[:content] if params[:image] @user.image_name = "#{@user.id}.jpg" image = params[:image] File.binwrite("public/user_images/#{@user.image_name}", image.read) end if @user.save flash[:notice] = "ユーザー情報を編集しました" redirect_to("/users/#{@user.id}") else render("users/edit") end end end
index.html.erb↓
<div class="row"> <% @users.each do |user| %> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title text-center"><%= link_to(user.name, "/users/#{user.id}") %></h3> </div> <%# ここはeach文の@postsがあるので@post.image_nameではなくpost.image_nameでいい%> <img src="<%= "/user_images/#{user.image_name}" %>" alt="" width="265" height="318" class="img-thumbnail img-post"> <button type="button" class="btn btn-warning"><%= link_to("詳細", "/users/#{user.id}") %></button> </div> </div> <% end %> </div>
new.html.erb↓
<div class="row"> <div class="col-sm-8 col-sm-push-4"> <h2 class="text-center"><strong><em> 研究者として登録</em></strong></h2> <%= form_tag("/users/create", {multipart: true}) do %> <div class="form-group"> <label for="Inputimage">写真</label> <input type="file" class="form-control" id="Inputimag" name="image"> </div> <button class="btn btn-warning" type="submit" value="投稿">登録</button> <% end %> </div>
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/09/24 14:09
2017/09/24 14:25 編集
2017/09/24 14:52
2017/09/24 14:56
2017/09/24 16:13
2017/09/25 00:58
2017/09/25 11:37