2013-05-29 55 views
0

我正在爲練習創建一個簡單的應用程序,我遇到了問題。我有一個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 

回答

1

你已經鏈接了表格,但沒有照片的setter getter。希望能幫助到你!!!

class Product < ActiveRecord::Base 
attr_accessible :description, :name, :photo 

belongs_to :user 
has_many :photos, dependent: :destroy 

validates :user_id,  presence: true 
validates :photo,  presence: true 
end 

如果:photo變量是不存在的產品型號,那麼你必須通過遷移創建照片產品數據庫表中的列中,你應該做這樣的事情:

$ rails g migration AddPhotoToProducts photo:string

+0

wouldnt它是rails g遷移AddPhotoToProducts照片:字符串替換遷移與遷移和製作複數? –

+0

排除解決我的問題的錯字。謝謝! –

+0

謝謝糾正了錯字! :) – uday

1

的錯誤信息是很清楚的:你在Product調用.photo,但是,你的Product有許多photos;注意's'。給定產品上沒有.photo。您需要使用product.photos,這是一個零或多個照片的類似數組的對象。