我有一个Rails应用程序,它有一个名为“Service”的模型,它与另一个名为“Upload”的模型有关联。服务has_many上传和上传belongs_to服务。 Uploads是一个使用paperclip gem为上传文件建模的模型。
以下是两者的Model类:
service.rb:
# == Schema Information
#
# Table name: services
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# last_run_time :datetime
# name :string(255)
# description :text
#
class Service < ActiveRecord::Base
attr_accessor :name, :description
has_many :uploads
end
upload.rb
# == Schema Information
#
# Table name: uploads
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# sourcedata_file_name :string(255)
# sourcedata_content_type :string(255)
# sourcedata_file_size :integer
# sourcedata_updated_at :datetime
# service_id :integer
#
class Upload < ActiveRecord::Base
has_attached_file :sourcedata
belongs_to :service
end
我使用rails关联的构造函数方法似乎没有用。
当我在rails控制台上运行时,我看到以下内容:
s = Service.new
=> #<Service id: nil, created_at: nil, updated_at: nil, last_run_time: nil, name: nil, description: nil>
>> > @u = s.upload.new
NoMethodError: undefined method `upload' for #<Service:0x007fc4c7818470>
>>@u = s.create_upload()
NoMethodError: undefined method `create_upload' for #<Service:0x007fc4c7818470>
>>@u = s.uploads.build
NoMethodError: undefined method `uploads' for #<Service:0x007fc4c7818470>
>> @u = s.uploads.create
NoMethodError: undefined method `uploads' for #<Service:0x007fc4c7818470>
我尝试使用这些方法创建关联的模型实例,但它似乎不起作用。我想知道我做错了什么。 请有人帮帮我。
由于
s.inspect =
=> "#<Service id: 6, created_at: \"2013-11-27 16:41:43\", updated_at: \"2013-11-27 16:41:43\",
last_run_time: nil, name: nil, description: nil>"
答案 0 :(得分:0)
请尝试以下操作:
s.uploads.build
s.uploads.create
答案 1 :(得分:0)
您正在使用has_many
,因此upload
方法不存在,因为您有很多方法......
使用s.uploads.new
(或s.uploads.build
)或s.uploads.create
并阅读ActiveRecord文档。
答案 2 :(得分:0)
你想:
s.uploads.build
和
s.uploads.create
您可以在这里阅读有关哪些方法:
http://guides.rubyonrails.org/association_basics.html#has-many-association-reference
4.3.1 has_many添加的方法
当您声明has_many关联时,声明类 自动获得与该关联相关的13种方法:
collection(force_reload = false)
collection<<(object, ...)
collection.delete(object, ...)
collection.destroy(object, ...)
collection=objects
collection_singular_ids
collection_singular_ids=ids
collection.clear
collection.empty?
collection.size
collection.find(...)
collection.where(...)
collection.exists?(...)
collection.build(attributes = {}, ...)
collection.create(attributes = {})