我的照片模型属于用户模型。每当我尝试访问/users/4/photos/new
的新视图时,Rails都会返回此错误:
No route matches {:action=>"index", :controller=>"photos", :user_id=>"4"} missing required keys: [:id]
这是我的 PhotosController :
class PhotosController < ApplicationController
def index
find_user
@photos = @user.photos
end
def new
find_user
@photo = @user.photos.build
end
def show
find_photo
end
def create
@photo = Photo.new(params[:photo])
if @photo.save
if params[:images]
params[:images].each { |image|
@user.photos.create(image: image)
}
end
else
render 'new'
end
end
def update
find_user
@photo = @user.photos.find(params[:id])
if @photo.update
redirect_to photos_path
else
render 'edit'
end
end
def destroy
find_photo
@photo.destroy
redirect_to photos_path
end
private
def find_user
@user = User.find(params[:user_id])
end
def find_photo
@photo = Photo.find(params[:id])
end
def photo_params
require(:photo).permit(:title, :image, :user_id)
end
end
这是照片视图的 _form 部分。
<%= form_for @photo, :html => { class: 'form-horizontal', multipart: true } do |f| %>
<%= f.label :title %>
<%= f.text_field :title, class: "input-field form-control" %>
<%= f.label :pictures %>
<%= file_field_tag "images[]", type: :file, multiplue: true %>
<%= f.submit nil, class: "btn btn-primary" %>
我不明白ID是如何丢失的,我通过 find_user 方法提供ID。
更新
# routes.rb
Rails.application.routes.draw do
root 'welcome#index'
# prevedene rute
get "/pocetna" => "welcome#index", as: "index"
get "/o-sajtu" => "welcome#about", as: "about"
get "/moj-profil" => "users#show", as: "profile"
post "/users" => "users#create"
get "/users" => "users#index", as: "users"
get "/user" => "users#index"
get "/users/:id" => "users#show", as: "user"
get "/users/:id/edit" => "users#edit", as: "edit_user"
patch "/users/:id" => "users#update"
get "/users/add" => "users#new", as: "new_user"
resources :sessions, only: [:new, :create, :destroy]
get "/login" => "sessions#new", as: "login"
post "/login" => "sessions#create"
get "/logout" => "sessions#destroy", as: "logout"
delete "/logout" => "sessions#destroy"
resources :users do
resources :photos
end
end
更新 我现在收到新错误
undefined method `photos_path' for #<<Class:0x007f4f14f16160>:0x00000004f040e8>
表格的第一行已标记。
答案 0 :(得分:1)
将_form partial中的form_for更改为
form_for([@user, @photo]) do |f|
#rest of your code
end
答案 1 :(得分:0)
如何在视图中调用/ users / 4 / photos / new?理想情况下,您应该将user_id作为id而不是user_id传递。有一次,你应该解决这个问题。