为了切中要点,我有两个模型:文章和照片(如下所示)。当我使用关联时,即(下图),为什么照片是多元化的?例如,如果我使用@article.user,它将显示user对象。我正在使用回形针btw。是不是因为文章可以有多个Photo实例(db中的多行)?
<% if @article.photos.exists? %>
<div class="row thumbnailrow">
<% @article.photos.each do |x| %>
<div class="col-xs-3">
<!--<img src="http://placehold.it/300x150" class="img-responsive"/>-->
<%= image_tag x.image.url(:full), :class=> "img-responsive" %>
</div>
<% end %>
</div>
<% end %>
class Article < ActiveRecord::Base
belongs_to :user
validates_presence_of :title,length: {minimum: 20, maximum:100}, :message =>" Enter a valid title. Minimum of 20 characters"
validates_presence_of :category, presence: true
#validates_presence_of :content, presence: true, length: {minimum: 500, maximum: 1000}
validates_associated :photos, :message => "Please use a valid image"
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, reject_if: proc { |attributes| attributes['image'].blank?}
def author
if user.present?
[user.first_name, user.last_name].reject(&:blank?).join(' ')
else
"author name"
end
end
end
class Photo < ActiveRecord::Base
has_attached_file :image, :styles => { :full => "640x480#", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "http://placehold.it/350x200"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
validates :image, :attachment_presence => true
belongs_to :article
end发布于 2014-10-15 23:38:39
Rails对它的关联很聪明,所以当你告诉它一个ActiveRecord模型has_many :photos时,它会理解即使只有一张照片附加,可能会有不止一张。如果要将关联更改为has_one :photo,它将不再是复数。讲得通?
https://stackoverflow.com/questions/26384367
复制相似问题