我是Ruby on Rails的新手,我一直在尝试创建一个样本苹果,但我一直坚持这一部分 WEEKS!我一直在垃圾邮件堆栈溢出但是我已经没有运气:(。 我正在尝试创建一个产品页面,该页面也允许多个图像上传。所以我有一个用户模型产品模型和照片模型。当我提交填写了照片和其他输入的表格时,我收到此错误。
NoMethodError in ProductsController#create
undefined method `photo' for #<Product:0x9078f74>
新产品页面
= form_for @product, :html => {:multipart => true} do |f|
%p
= f.label :description
= f.text_field :description
= fields_for @photo, :html => {:multipart => true} do |fp|
= fp.file_field :image
%p.button
= f.submit
产品控制器
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])
end
产品型号
attr_accessible :description, :name, :photo, :image
belongs_to :user
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos
validates :user_id, presence: true
validates :description, presence: true
validates :photo, presence: true
end
照片模型
attr_accessible :image
belongs_to :product
validates_attachment :image, presence: true
用户模型
attr_accessible :email, :name, :password, :password_confirmation, :image, :photo
has_many :products, dependent: :destroy
has_many :photos, :through => :products
end
表
用户
产品
照片
答案 0 :(得分:4)
将产品控制器更改为
def new
@product = Product.new
@product.photos.build
end
def create
@product = Product.new(params[:product])
end
由于您要求多张图片上传,请尝试将其添加到您的视图中
<%= f.fields_for :photos do |img| %>
<%= render "img_fields", :f => img %>
<% end %>
<div class="add_image"><%= link_to_add_fields "Add Image", f, :photos %></div>
并为视图创建文件_img_fields.html.erb并添加
<div class="entry_field">
<label>Image :</label>
<%= f.file_field :image %>
<%= link_to_remove_fields "remove", f %></div>
然后将以下行添加到application.js文件
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".entry_field").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
在您的产品型号中
has_many :photos
accepts_nested_attributes_for :photos
attr_accessible :description, :name, :photos_attributes
答案 1 :(得分:1)
变化:
= fields_for @photo, :html => {:multipart => true} do |fp|
要:
= fields_for :photos, :html => {:multipart => true} do |fp|
在你的控制器中:
def new
@product = Product.new
@product.photos.build
end
在您的产品型号中:
attr_accessible :description, :name, :photos_attributes
答案 2 :(得分:1)
在您的产品型号中
has_many:照片
accepts_nested_attributes_for:照片
attr_accessible:description,:name,:photos_attributes