我正在爲練習創建一個簡單的應用程序,我遇到了問題。我有一個3模型。用戶建模產品模型和照片模型。用戶has_many產品和產品has_many照片。到目前爲止這麼好,但當我嘗試提交新產品時出現此錯誤。Rails模型關聯 - 幫我解決這個問題
NoMethodError中的ProductsController#創建
未定義的方法`照片」爲#(產品: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
wouldnt它是rails g遷移AddPhotoToProducts照片:字符串替換遷移與遷移和製作複數? –
排除解決我的問題的錯字。謝謝! –
謝謝糾正了錯字! :) – uday