Rails模型关联 - 帮我解决这个问题

时间:2013-05-29 02:56:06

标签: ruby-on-rails ruby ruby-on-rails-3

我正在为练习创建一个简单的应用程序,我遇到了问题。我有3个型号。用户建模产品模型和照片模型。用户拥有很多产品和产品,有很多照片。到目前为止这么好但我在尝试提交新产品时遇到此错误。

  

ProductsController中的NoMethodError #create

     

#(产品:0xb69a6f8)

的未定义方法`photo'

产品控制器

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

2 个答案:

答案 0 :(得分: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变量,那么您必须使用迁移在Products db表中为照片创建一列,因为您应该这样做:

$ rails g migration AddPhotoToProducts photo:string

答案 1 :(得分:1)

错误消息非常清楚:您在.photo上调用了Product,但是,Product有许多photos;注意's'。给定产品没有.photo。您需要使用product.photos,这是一个零个或多个照片的类似数组的对象。