【问题标题】:Rails model association - Help me fix this issueRails 模型关联 - 帮我解决这个问题
【发布时间】:2013-05-29 02:56:05
【问题描述】:

我正在创建一个简单的练习应用程序,但我遇到了问题。我有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

【问题讨论】:

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


    【解决方案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
    

    如果 Product 模型中没有 :photo 变量,那么您必须使用迁移在 Products db 表中为照片创建一个列,因为您应该这样做:

    $ rails g migration AddPhotoToProducts photo:string

    【讨论】:

    • 难道不是 rails g migration AddPhotoToProducts photo:string 用 migration 替换 migrate 并使 product 复数吗?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      相关资源
      最近更新 更多