0

我希望有人能给我一些关于如何嵌套资源的见解,更具体地说,如何将它与 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

谢谢参观。任何帮助深表感谢。

4

1 回答 1

1

我对你的代码做了一些调整。

请注意,我在动物中添加了一个“s”

root to: "home#index"

resources :animals do
  resources :photos
end

注意我已经从动物身上删除了一个“s”。我已将 animal_permalink 更改为 id ,因为这是嵌套资源所期望的默认值。另外,请注意,在您的照片控制器新方法中,您检查“id”参数,而不是 animal_permalink 参数。

new_animal_photo_path(id: "dog")

在你的_form中。设置 animal_permalink 的值

<%= f.hidden_field :animal_permalink, value: @animal.permalink %>

这假设 Photo 能够识别 animal_permalink 属性并且您已经定义了 animal.permalink 方法/属性。我不熟悉永久链接方法,因此您可能需要稍微摆弄一下,但这应该会引导您朝着正确的方向前进(我通常会设置 :dog_id/:animal_id 属性)。

让我知道情况如何。

于 2013-05-26T00:47:54.310 回答