我在stackoverflow搜索解決方案,但每次都有不同的問題,所以我決定問這個問題。 在我的申請中,我有Travel,它有許多帖子。一個用戶可以創建許多旅行,並在一次旅行中發佈很多帖子。 但是當我嘗試創建一個帖子,我有這樣的錯誤:ActiveRecord無法找到與'id'旅行=
ActiveRecord::RecordNotFound in PostsController#create
Couldn't find Travel with 'id'=
我不明白爲什麼,因此,如果有人可以幫助我.. 這是我Posts_controller.rb(create動作):
def create
@travel = Travel.find(params[:id])
@post = @travel.posts.new(posts_params)
@post.user = current_user
if @post.save
flash[:success] = "Your post is published"
redirect_to user_path(current_user)
else
render 'new'
end
end
這裏是我的模型:
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :travel
geocoded_by :country
after_validation :geocode
end
class Travel < ApplicationRecord
has_many :posts
belongs_to :user
end
我的路線:
# Travel
resources :travels, :shallow => true do
# Posts
resources :posts
end
而對於形式的LIGNE:
<%= form_for(@post, :html => {class: "form-horizontal", role: "form"}, :url => travel_posts_path(@travel)) do |f| %>
<div class="form-group">
<%= f.text_field :travel_id, placeholder: @travel.id %>
</div>
你爲什麼要讓用戶處理'id's?這是一個不好的做法。 – Dbz
我會建議調試'params'。您可能需要執行諸如'params [:travel_id]'之類的操作。但我仍然不會允許用戶選擇'id's。 – Dbz
@Dbz我只是嘗試在我的表格文章的travel_id列中添加旅行ID,表格中的字段只是在這裏幫助我,我將在它的工作時刪除該行 –