ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-Build login environment with devise -Posting function that only logged-in users can do
We will assume that the posting function has already been created.
1 Introduction of gem refile Add 2 columns 3 Edit model 4 Editing controller 5 Edit view
Gemfile
gem 'refile', require: 'refile/rails', github: 'refile/refile'
Terminal
$ bundle install
Terminal
$ rails g migration AddPostImageIdToPosts post_image_id:string
Terminal
$ rails db:migrate
It is OK if t.string "post_image_id" is added.
db/schema
create_table "posts", force: :cascade do |t|
t.integer "user_id"
t.string "title"
t.string "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "post_image_id" # <--OK with this
t.index ["user_id"], name: "index_posts_on_user_id"
end
app/models/post.rb
attachment :post_image
You can also change the post_image by adding the following.
app/controllers/posts_controller.rb
def post_params
params.require(:post).permit(:title, :body, :post_image)
end
This time, to display the default image first, I prepared an image file called no-image.png in advance. The save location will be in app / assets / images.
erb:app/views/posts/new.html.erb
<% form_with,...%>
...
<div>
<%= attachment_image_tag @post, :post_image, fallback: "no-image.png ", id: "img_prev", style: "height: 250px; width:300px;" %><br>
<%= f.attachment_field :post_image %>
</div>
...
<% end %>
...
<script>
$(document).on("turbolinks:load", function(){
function readURL(input) {
if(input.files && input.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#post_post_image").change(function(){
readURL(this);
});
});
</script>
Refile.secret_key = ...
Is displayed.
Copy the line containing that Refile.secret_key = and
In config / initializers / application_controller_renderer.rb
You can eliminate the error by adding it at the bottom.
</details>
Recommended Posts