我希望有人能给我一些关于如何嵌套资源的见解,更具体地说,如何将它与 CarrierWave 联系起来。
我遇到了一个错误undefined method 'photos_path'
,并且有点坚持如何让它发挥作用。
我希望能够拥有以下网址
创建一张新照片
site.com/animal/dog/photos/new
显示照片
site.com/animal/dog/photos/my-dog-in-the-park
我应该使用嵌套表单吗?任何帮助深表感谢。
我的路线
root to: "home#index"
resources :animal do
resources :photos
end
我家的景色
<%= link_to "Add Dog Photo", new_animal_photo_path(animal_permalink: "dog") %>
我的 _form 部分
<%= form_for [@animal, @photo], :html => {:multipart => true} do |f| %>
<%= f.hidden_field :animal_permalink %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.file_field :image %>
</p>
<p>
</p>
<p><%= f.submit %></p>
<% end %>
我的照片模型
class Photo < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
before_create :set_permalink
before_update :set_permalink
belongs_to :dog
mount_uploader :image, PhotoUploader
def set_permalink
self.permalink = title.parameterize
end
def to_param
permalink.parameterize
end
end
我的动物模型
class Animal < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
has_many :photos
scope :dog, where(name: "Dog")
def to_param
permalink.parameterize
end
end
我的照片控制器
class PhotosController < ApplicationController
def show
@photo = Photo.find(params[:id])
end
def new
@animal = Animal.find_by_permalink(params[:id])
@photo = Photo.new
end
def create
@photo = Photo.new(photo_params)
if @photo.save
flash[:notice] = "Successfully created photo."
redirect_to root_url
else
render :action => 'new'
end
end
def edit
@photo = Photo.find(params[:id])
end
def update
@photo = Photo.find(params[:id])
if @photo.update_attributes(photo_params)
flash[:notice] = "Successfully updated photo."
redirect_to root_url
else
render :action => 'edit'
end
end
def destroy
@photo = Photo.find(params[:id])
@photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to root_url
end
private
def photo_params
params.require(:photo).permit(:title, :image, :animal_id)
end
end
谢谢参观。任何帮助深表感谢。