我有一个名为Notifications的模型,它基本上充当请求和住宿之间的连接表。
在我的Requests控制器中的“create”方法中,我有:
# find associated accommodations, currently matching: location
@accommodations = Accommodation.where('location' => :location)
@accommodations.each do |accommodation|
@notification = @request.notification.build('accommodation_id' => accommodation.id ).save
end
似乎没有创建新的通知记录。我在这里做错了什么?
模型/ accommodation.rb
class Accommodation < ActiveRecord::Base
validates_presence_of :title, :description, :thing, :location, :spaces, :price, :photo
attr_accessible :photo_attributes, :title, :description, :thing, :location, :spaces, :price
has_one :photo
has_many :notifications
belongs_to :user
accepts_nested_attributes_for :photo, :allow_destroy => true
end
模型/ notification.rb里
class Notification < ActiveRecord::Base
attr_accessible :accommodation_id, :request_id
has_one :request
end
模型/ request.rb
class Request < ActiveRecord::Base
attr_accessible :firstname, :lastname, :email, :phone, :datestart, :dateend, :adults, :children, :location, :status
validates_presence_of :firstname, :lastname, :email, :phone, :datestart, :dateend, :children, :adults, :location
has_many :notifications
end
答案 0 :(得分:1)
@request.notification.build
应为@request.notification
s .build
。
此外,您要将@notification
设置为.save返回的值,该值仅为true
或false
。如果希望create
指向实际对象,则可能需要使用@notification
。另外,您可能已经知道它将在每次迭代时覆盖@notification
变量,您可能想要也可能不想要。
关于提供的示例有很多要说的,我认为实现完全不好。但这与通知记录未保存的原因无关。
答案 1 :(得分:0)
您没有在控制器中定义@request或:location。假设它是一个Request对象:
@notifications = Array.new
@accommodations = Accommodation.where('location' => :location)
Accommodation.find_each(:conditions => { 'location' => :location }) do |a|
notification = @request.notifications.create('accommodation_id' => a.id)
@notifications << notifications
end
就像@AnomalousThought所说:
关于这一点有很多话要说 提供的例子,我认为 实施完全不好。但 这与问题无关 为什么通知记录没有保存。