我正在使用回形针宝石。用户可以使用图像提交位置。我不希望用户复制已经提交的位置,但是他们可以向其中添加图片。
我一直试图找出答案。我将在下面留下重要的代码:
class Location < ApplicationRecord
has_many :submissions
has_many :users, through: :submissions
# Allows submission objects
accepts_nested_attributes_for :submissions
class Submission < ApplicationRecord
belongs_to :user
belongs_to :location
has_attached_file :image, styles: { large: "600x600>", medium: "300x300>", thumb: "150x150#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
class LocationsController < ApplicationController
# Before actions get routed and ran, find_location will occur
before_action :find_location, only: [:show, :edit, :update, :destroy]
# For the Locations/index.html.erb
def index
@locations = Location.all
end
# Binds submission object to the form in new.html.erb
def new
@locations = Location.new
@locations.submissions.build
end
# For creating a new location in the new.html.erb form
def create
@locations = Location.new(user_params)
# Everything went well. User will be sent to @locations show page
if @locations.save
# Redirects to user submitted locations
redirect_to @locations
else
render 'new'
end
end
# Finds new location user submitted by its unique id
def show
end
# Allowing user to update their submitted location
def edit
end
# Updates users edited submission
def update
if @locations.update(user_params)
# Redirects to user submitted locations
redirect_to @locations
else
render 'edit'
end
end
# Deletes users submission
def destroy
@locations.destroy
# Redirects to user submitted locations
redirect_to @locations
end
private
# Used for finding user submitted location (Prevents DRY)
def find_location
@locations = Location.find(params[:id])
end
# Strong parameters for security - Defines what can be update/created in location model
def user_params
params.require(:location).permit(:city, :state, :submissions_attributes => [:image])
end
end
<%= form_for @locations, html: {multipart: true} do |f| %>
.
.
.
<!-- User enters image-->
<%= f.fields_for :submissions do |s| %>
<div class="form-group">
<h3>Upload Image:</h3>
<%= s.file_field :image, class: 'form-control' %>
</div>
<% end %>
<% end %>
<h3>Image: <%= image_tag @locations.image.url(:medium) %></h3>
我得到一个错误:
"undefined method `image' for.."
答案 0 :(得分:2)
您似乎正在尝试为记录的集合制作表单标签,我认为这不起作用。相反,我认为您需要一个类似以下的结构:
<% @locations.each do |location| %>
<%= form_for location, html: {multipart: true} do |f| %>
.
.
.
<!-- User enters image-->
<%= f.fields_for location.submissions.new do |s| %>
<div class="form-group">
<h3>Upload Image:</h3>
<%= s.file_field :image, class: 'form-control' %>
</div>
<% end %>
<% end %>
form_for
和fields_for
都需要指向单个资源。
旁注:Paperclip has been deprecated,建议您改用Rails内部ActiveStorage。