我一直在尝试不同的解决方案。但似乎没有任何效果
背景信息:对于我的应用,用户可以上传图片,每个图片都可以拥有多个用户。所以它通过以下方式进行多对多关联:。 我遇到的问题是从表单收到的信息/数据不会保存在数据库中。
我正在使用茧宝石。上传图像时,我可以在前端添加和删除用户字段。当我上传图像,并选择user1和user2时,调试器显示我收到了user_id1和user_id2。提交后,我使用rails console来检查image.users。但它是空的,没有用户与图像相关联。我做了很多研究,并尝试了许多不同的方法,但似乎没有任何工作。
调试器显示从表单收到user_ids。
{"utf8"=>"✓", "authenticity_token"=>"/q52XogfTcEqCLap3K5C4B4I1gNYQGfBJOynNvdIXUE3ViVnRM+2JcksmaAwCWzBXw2kSOqOR+W25pefgBRRGw==", "image"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0x007f49998bd320 @tempfile=#<Tempfile:/tmp/RackMultipart20170103-11352-qmm06k.png>, @original_filename="erincolor4.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"image[picture]\"; filename=\"erincolor4.png\"\r\nContent-Type: image/png\r\n">, "image_users_attributes"=>{"1483469430746"=>{"user_id"=>"1", "_destroy"=>"false"}, "1483469434072"=>{"user_id"=>"9", "_destroy"=>"false"}}}, "commit"=>"Upload", "controller"=>"images", "action"=>"create"}
我怀疑问题不是形式,而是模型或控制器。
#Image model
class Image < ActiveRecord::Base
attr_accessor :picture, :image_users_attributes, :user_id
has_many :image_users, dependent: :destroy
has_many :users, through: :image_users
accepts_nested_attributes_for :image_users, reject_if: :all_blank, allow_destroy: true
mount_uploader :picture, ImageUploader
validates :picture, presence: true
validates_associated :image_users
end
#User model
class User < ActiveRecord::Base
has_many :image_users
has_many :images, through: :image_users
end
#ImageUser model
class ImageUser < ActiveRecord::Base
belongs_to :user
belongs_to :image
end
图像控制器
class ImagesController < ApplicationController
before_action :set_image, only: [:show, :destroy, :edit, :update]
before_action :require_user, only: [:new, :create, :edit, :update, :destroy]
def new
@image = Image.new
end
def create
debugger
@image = Image.new(image_params)
if @image.save
flash[:success]="Image saved"
redirect_to user_path(current_user)
else
render'new'
end
end
...........
private
def image_params
params.require(:image).permit(:picture, image_users_attributes:[:id, :user_id, :_destroy])
end
def set_image
@image =Image.find(params[:id])
end
end
表单视图:
<%= form_for @image do |f|%>
<div class="field">
<%= f.file_field :picture, accept: 'image/jpeg, image/gif, image/png'%>
</div>
<div id='image_users'>
<%= f.fields_for :image_users do |u| %>
<%=render 'image_user_fields', :f => u %>
<% end %>
<div class="links">
<%= link_to_add_association 'add user', f, :image_users %>
</div>
</div>
<%= f.submit 'Upload' %>
<% end %>
#nested form
<div class="nested-fields">
<div class="field">
<%= f.label :content,"Stylist" %><br>
<%= f.collection_select :user_id, User.all, :id,:username, :prompt => " " %>
</div>
<%= link_to_remove_association "remove stylist", f %>
</div>
我正在使用cloud9 IDE
答案 0 :(得分:0)
我弄明白了这个问题。当我观看视频时,我看到了attr_accessible,但是当我运行服务器时,它给我一个错误,并建议attr_accessor。所以我把它改成了attr_accessor。不要犯这个愚蠢的错误。但是,如果有人能告诉我为什么attr_accessor使我的代码不起作用,那就太棒了:)