【问题标题】:Rails Nested Attributes pluralization when using associations?使用关联时Rails嵌套属性复数?
【发布时间】:2014-10-15 13:55:20
【问题描述】:

为了保持重点,我有两个模型:文章和照片(下)。当我使用关联时,即(下),为什么照片是复数的?例如,如果我做了@article.user,它将显示用户对象。我正在使用回形针顺便说一句。是不是因为文章可以有很多照片的实例(数据库中的多行)???

 <% 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多