I'm creating a basic house listing page to get to grips with Rails and I'm trying to work out how I would add a image file uploader to a simple_form gem on Ruby on Rails.
Currently, I have a basic form which asks for a title, price and description, whilst I was creating the form I added an input field for image but instead of an input field, I would like to allow a user to add an image file which would be added to the listing with house.image
My code is as follows:
index.html.erb -
<p><%= link_to "Add a House", new_house_path %></p>
<% @houses.each do |house| %>
<div class="house">
<p><%= house.image %></p>
<h2><%= house.title %></h2>
<h2><%= house.price %></h2>
<p><%= house.description %></p>
</div>
<% end %>
<p><%= paginate @houses %></p>
house.rb -
class House < ActiveRecord::Base
validates :title, presence: true
validates :price, presence: true
validates :description, presence: true
validates :image, presence: true
end
houses_controller.rb -
class HousesController < ApplicationController
def index
@houses = House.page(params[:page]).per(20).order(created_at: :desc)
end
def new
@house = House.new
end
def create
@house = House.new(params.require(:house).permit(:title, :price, :description, :image))
if @house.save
redirect_to root_path
else
render "new"
end
end
end
new.html.erb -
<%= simple_form_for @house do |form| %>
<%= form.input :title, label: "House title" %>
<%= form.input :price, label: "House price" %>
<%= form.input :description, label: "Describe your house" %>
<%= form.input :image, label: "Image of house" %>
<%= form.button :submit %>
<% end %>
You should be able to change:
<%= form.input :image, label: "Image of house" %>
to
<%= form.input :image, as: :file, label: "Image of house" %>
This will create a standard HTML file input field which allows your users to select local files for upload. There are information about this and other field types available Simple Form input field types .
Additionally, you will want to consider a gem such as Paperclip or Carrierwave to handle receiving files on the server (in the model).
And if you really want a custom input type in simple_form, you can read about how to implement that in the simple_form github repo under "Custom Inputs" -- this would NOT be necessary for uploading an image. It would be syntactic sugar for your code.
For image upload you can use paperclip
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.