我正在创建一个简单的练习应用程序,但我遇到了问题。我有3个模型。用户模型一个产品模型和一个照片模型。一个用户有_many 产品和产品有_many 照片。到目前为止一切顺利,但是当我尝试提交新产品时出现此错误。
ProductsController#create 中的 NoMethodError
#(Product:0xb69a6f8) 的未定义方法“照片”
产品控制器
def new
@product = Product.new
@photo = Photo.new
end
def create
@photo = current_user.photos.build(params[:photo])
@product = current_user.products.build(params[:product])
if @product.save
render "show", :notice => "Sale created!"
else
render "new", :notice => "Somehting went wrong!"
end
end
产品型号
class Product < ActiveRecord::Base
attr_accessible :description, :name
belongs_to :user
has_many :photos, dependent: :destroy
validates :user_id, presence: true
validates :photo, presence: true
end
照片模型
class Photo < ActiveRecord::Base
belongs_to :product
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'] },
size: { less_than: 5.megabytes }
has_attached_file :image, styles: { medium: "320x240>"}
end
用户模型
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
has_many :products, dependent: :destroy
has_many :photos, :through => :products
validates :name, presence: true, length: { minimum: 5 }
validates :email, presence: true, length: { minimum: 5 }, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
end
我的超级简单的新产品视图
= form_for @product do |f|
%p
= f.label :name
= f.text_field :name
%p
= f.label :description
= f.text_field :description
%p.button
= f.submit