Rails 4 - 当它是嵌套路由时,在控制器中“创建”动作

时间:2015-02-26 06:22:56

标签: ruby-on-rails rest

我有一个用户模型has_many Photos(另一个模型)。在routes.rb文件中,它的照片是用户的嵌套资源。所以,我有一个form_for上传到控制器#create action。我在将照片保存到用户下的数据库时遇到问题。我怎样才能做到这一点?它说它保存正确,因为它重定向,但它没有显示它有一张照片(我也使用控制台检查不仅仅是我的视图)。我做错了什么?

class PhotosController < ApplicationController
  def new
    @photo = Photo.new(:user_id => params[:user_id])
  end

  def create
    byebug
    @photo = Photo.new(params[:user_id])
    if @photo.save
      flash[:notice] = "Successfully added photo."
      redirect_to new_user_photo_path
    else
      render :action => 'new'
    end
  end
end

EDIT ----------

添加form_for,让我们进入#create动作。希望这会有所帮助:)我已经阅读了更多相关内容,而且我还不确定该怎么做才能修复。

<%= form_for @photo, :url => user_photos_path(current_user.id, @photo), :html => {:multipart => true} do |f| %>
  <div class="form-group">
    <%= f.file_field :image %>
  </div>
  <%= f.submit 'Upload', class: 'btn btn-success' %>
  &nbsp;or
  <%= link_to 'Cancel', users_path %>
<% end %>

1 个答案:

答案 0 :(得分:0)

class PhotosController < ApplicationController
  def new
    @user = User.find(params[:user_id])
    @photo = Photo.new(:user_id => params[:user_id])
    @photos = @user.photos
  end

  def create
    @photo = User.find(params[:user_id]).photos.new(photo_params)
    if @photo.save
      flash[:notice] = "Successfully added photo."
      redirect_to new_user_photo_path
    else
      render :action => 'new'
    end
  end

  # GET /photos
  def index
    redirect_to new_user_photo_path
  end


  # GET /photos/1
  def show
    @photo = Photo.find(params[:id])
  end

  def edit
    @photos = Photo.all
    @photo = Photo.new
  end

  def destroy
    @photo = User.find(params[:user_id]).photos.find(params[:id])
    @photo.destroy
    flash[:notice] = "Successfully deleted photo"
    redirect_to new_user_photo_path
  end

  def photo_params
    params.require(:photo).permit!
  end

end