这是一个相当令人沮丧的新问题,但我似乎无法让对象迭代在我的rails项目中工作。我有两个模型,“照片”和“土地使用”都有一个has_和_属于_many协会。在控制台中一切都按预期工作。
<% for use in @photo.land_uses %>
<%= use.name %>
<% end %>
这不会产生任何输出。我也试过:
<% @photo.land_uses.each do |use| %>
<%= use.name %>
<% end %>
在控制台中,如果我尝试以下操作:
photo = Photo.first
photo.land_uses
我得到了这张照片所属的所有土地用途的清单,没有什么意外。
那么,我如何遍历使用列表并打印每个使用的名称呢?
foreach($photo->land_uses as $use) {
echo $use->name;
}
那么我在这里遗漏了什么?
--照片模型--
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :transect
belongs_to :focus
has_and_belongs_to_many :land_uses
validates :caption, :presence => true
validates :place, :presence => true
validates :city, :presence => true
validates :country, :presence => true
has_attached_file :file,
:processors => [:watermark],
:styles => { :standard => "631x631>",
:marked => { :geometry => "631x631>", :watermark_path => "#{Rails.root}/public/images/watermark.png", :position => 'Center' },
:thumbnail => "174x130#"
},
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => ":user_id/:year/:month/:id/:style.:extension"
geocoded_by :location, :latitude => :lat, :longitude => :lng
after_validation :fetch_coordinates
def location
[place,city,state,country].delete_if{|val| val==''||nil}.join(', ')
end
end
--土地利用模式--
class LandUse < ActiveRecord::Base
has_and_belongs_to_many :photos
validates_uniqueness_of :name
end
回复:错误消息。。。
谢谢!