我想構建一個示例應用程序,其中用戶可以將兩種不同類型的圖像上傳到名爲Article的模型。一種類型的圖像是文章內容中使用的圖像,另一種用作縮略圖。這兩種類型的圖像都是由名爲ArticleImage和ArticleThumb的獨立多態模型處理的。Rails carrierwave - 無法批量分配受保護的屬性錯誤
問題是,每當我嘗試上傳縮略圖時,它都會給我提供「無法批量保護受保護的屬性::article_thumb」的錯誤。對於其他類型的圖像上傳,此錯誤不會發生。
文章
class Article < ActiveRecord::Base
attr_accessible :title, :article_images_attributes,
:article_thumbs_attributes
has_many :comments, as: :commentable
has_many :article_images, as: :attachable, dependent: :destroy
has_many :article_thumbs, as: :attachable, dependent: :destroy
accepts_nested_attributes_for :article_images,
reject_if: :all_blank,
allow_destroy: true
accepts_nested_attributes_for :article_thumbs, allow_destroy: true
belongs_to :user
validates :title, presence: true, length: {maximum: 60}
validates :user_id, presence: true
validates :article_images, presence: true
end
ArticleImage
class ArticleImage < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
attr_accessible :article_image
mount_uploader :article_image, ArticleImageUploader
end
ArticleThumb
class ArticleThumb < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
attr_accessible :article_thumb
mount_uploader :article_thumb, ArticleThumbUploader
end
new.html.erb
<%= simple_nested_form_for @article, html: {multipart: true},
defaults: {required: false} do |f| %>
<%= render 'shared/error_messages', object: @article %>
<%= f.input :title %>
<div class = "control-label">
Image file upload
</div>
<%= f.simple_fields_for :article_images do |p| %>
<%= p.file_field :article_image %>
<%= p.link_to_remove 'Remove' %>
<% end %>
<%= f.link_to_add 'Add image', :article_images %>
<span class="hint_end">Acceptable file formats: JPG, JPEG, GIF, PNG</span>
<div class = "control-label">
Thumbnail upload
</div>
<%= f.file_field :article_thumb %>
<span class="hint">
Automatically resized to 90x90 px.
</span>
<span class="hint">
Default thumbnail is used if no thumbnail gets uploaded.
</span>
<span class="hint_end">
Acceptable file formats: JPG, JPEG, GIF, PNG
</span>
<%= f.submit "Upload article" %>
<% end %>
我有一種感覺,這個錯誤只需要一個很簡單的修復,但我似乎無法弄清楚。任何幫助,將不勝感激。
作爲一個便箋,我想知道將所有不同的上傳器安裝在單個多態模型中是否有效,因此您不必在每次上傳不同類型的圖像文件。如果你沒有太多時間,你當然不需要費心回答這個問題,但是對這個問題的任何評論都是值得歡迎的!
感謝您指出。但是,問題仍然存在。 – jeebface 2013-03-11 20:21:42
那麼,爲什麼不在'simple_fields_for'塊中包裝'<%= f.file_field:article_thumb%>'?在你的情況'article_thumb'應該是文章的屬性,而不是article_thumb的。 – 2013-03-11 20:34:17
這是我醒來後第一次嘗試,現在我在Article#new中添加了@ article.article_thumbs.new。謝謝你的時間。 – jeebface 2013-03-11 21:18:41