首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当使用关联时,Rails嵌套属性的复数?

当使用关联时,Rails嵌套属性的复数?
EN

Stack Overflow用户
提问于 2014-10-15 21:55:20
回答 1查看 62关注 0票数 0

为了切中要点,我有两个模型:文章和照片(如下所示)。当我使用关联时,即(下图),为什么照片是多元化的?例如,如果我使用@article.user,它将显示user对象。我正在使用回形针btw。是不是因为文章可以有多个Photo实例(db中的多行)?

代码语言:javascript
运行
复制
 <% 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
EN

回答 1

Stack Overflow用户

发布于 2014-10-15 23:38:39

Rails对它的关联很聪明,所以当你告诉它一个ActiveRecord模型has_many :photos时,它会理解即使只有一张照片附加,可能会有不止一张。如果要将关联更改为has_one :photo,它将不再是复数。讲得通?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26384367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档