我想將圖像添加到模型中。我有用戶設置Devise,他們have_many
他們正在銷售的項目。Ruby on Rails - 圖片上傳
我現在想將一個圖像數組添加到Item模型(不知道這是否是最好的方法)。
我看了一個回形針,但只能做一個圖像。也看過載波,但不知道如何在現有模型上實現。
這是我的一些代碼。
item.rb的
class Item < ActiveRecord::Base
belongs_to :user
validates :title, presence: true
validates :price, presence: true
validates :description, presence: true
end
items_controller.rb
class ItemsController < ApplicationController
before_action :findItem, only: [:edit, :update, :sold]
def index
@items = Item.all
end
def new
@item = Item.new
end
def create
@item = Item.create(item_params)
@item.user = current_user
if @item.save
flash[:success] = "Your item was successfully listed."
render 'show'
else
flash[:error] = "Your item could not be listed. Please try again."
render 'new'
end
end
def show
@item = Item.find(params[:id])
end
def edit
end
def update
if @item.update(item_params)
flash[:success] = "Your item listing was updated successfully."
redirect_to item_path(@item)
else
flash[:error] = "Your listing was not updated. Please try again."
render 'edit'
end
end
def sold
@item.toggle(:sold)
@item.save
redirect_to item_path(@item)
end
private
def item_params
params.require(:item).permit(:title, :price, :description)
end
def findItem
@item = Item.find(params[:id])
end
end
表格項目/ new.html.erb
<div class="row">
<div class="col-xs-12">
<%= form_for(@item, :html => {class: "form-horizontal", role: "form"}) do |f| %>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :title %>
</div>
<div class="col-sm-8">
<%= f.text_field :title, class: "form-control", placeholder: "What are you selling?", autofocus: true %>
</div>
</div>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :price %>
</div>
<div class="col-sm-8">
<%= f.number_field :price, class: "form-control" %>
</div>
</div>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :description %>
</div>
<div class="col-sm-8">
<%= f.text_area :description, rows: 10, class: "form-control", placeholder: "Describe your item. The more detail you include, the more likely it is to sell." %>
</div>
</div>
<div class="form-group">
<div class="center col-sm-offset-1 col-sm-10">
<%= f.submit class: "btn btn-primary btn-lg" %>
</div>
</div>
<% end %>
<div class="center col-xs-4 col-xs-offset-4">
<%= link_to "[ Cancel and return to listing page ]", items_path %>
</div>
那正是我所需要的。我會明天實施它,看看它是如何發展的。對於這些視圖,他們可以通過「@ item.images.each」訪問,然後遍歷? –
如果你想*顯示*上傳圖片,你必須使用'@item.images.each do | image | <%= image_tag image.picture.url%> end' - 我可以看看如何將'picture.url'方法委託給您的圖片,但由於它是'has_many',所以它會非常棘手 –