Rails嵌套属性在使用关联时是多元化的?

时间:2014-10-15 13:55:20

标签: ruby-on-rails model paperclip nested-attributes

为了说明问题,我有两个模型:文章&照片(下图)。当我使用关联,即(下面)时,为什么照片会复数?例如,如果我做了@ article.user,它将显示用户对象。我正在使用Paperclip 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

1 个答案:

答案 0 :(得分:0)

Rails对它的关联是明智的,所以当你告诉它一个ActiveRecord模型has_many :photos它理解即使只附加一张照片,也可能有不止一个。如果您要将关联更改为has_one :photo,则不再是复数。有意义吗?