所以,我想在我的视图中添加一个收藏按钮来显示实习,但是我得到了这个错误:{:favorite_internship=>“必须存在”}
我不知道如何告诉rails显示视图实习的id是favorite_internship_id
我已经在实习生控制器中尝试过了,但它不起作用
@favorite.favorite_internship_id = @internship.id
首先,表最受欢迎,Internship的class_name为'favorite_internship‘,User的class_name为'favorite_user’
create_table "favorites", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "favorite_user_id"
t.bigint "favorite_internship_id"
t.index ["favorite_internship_id"], name: "index_favorites_on_favorite_internship_id"
t.index ["favorite_user_id"], name: "index_favorites_on_favorite_user_id"
end最喜欢的模型
class Favorite < ApplicationRecord
belongs_to :favorite_user, class_name: "User"
belongs_to :favorite_internship, class_name: "Internship"
end实习模式
class Internship < ApplicationRecord
has_many :favorites, foreign_key: "favorite_internship_id"
has_many :favorite_users, foreign_key: "favorite_user_id", class_name: "User", through: :favorites
end收藏夹控制器
class FavoritesController < ApplicationController
def new
@favorite = Favorite.new
end
def create
@favorite = Favorite.new(favorite_internship_id: params[:favorite_internship_id], favorite_user_id: params[:favorite_user_id])
@favorite.favorite_user = current_user
respond_to do |format|
if @favorite.save
format.html { redirect_back fallback_location: root_path, notice: 'Favorite was successfully created.' }
format.json { render :show, status: :created, location: @favorite }
else
format.html { redirect_back fallback_location: root_path, notice: "Le favoris n'a pas pu être créé : #{@favorite.errors.messages}" }
format.json { render json: @favorite.errors, status: :unprocessable_entity }
end
end
end
end所以最喜欢的按钮是在实习生节目中。这是实习控制器:
class InternshipsController < ApplicationController
def show
@reviews_of_internship = @internship.reviews.order(created_at: :desc).paginate(page: params[:page], per_page: 4)
@review = Review.new
@favorite = Favorite.new
@favorite.favorite_internship_id = @internship.id
end
end路线
resources :favorites
resources :internships do
resources :reviews, only: [:new, :create, :edit, :update, :destroy]
resources :favorites, only: [:new, :create, :destroy]
end创建收藏夹路由为:
internship_favorites POST /internships/:internship_id/favorites(.:format) favorites#create我在视图中有一个‘收藏夹’按钮可以点击,这样实习生就会受到青睐
<%= button_to "Favorite", internship_favorites_path(@internship), method: :post %>这就是我收到错误‘{:favorite_internship=>’必须存在‘}’的地方。
所以,如果你对此有什么建议,那就是我该怎么做。按钮是一个好主意,还是我应该做其他的事情?
发布于 2020-05-06 20:38:47
你有favorite_internship模型吗?如果是,则必须在属于收藏的模型中添加
belongs_to :favorite, optional: true发布于 2020-05-06 22:05:44
问题解决了!我没有把这个代码:
@favorite.favorite_internship_id = @internship.id在正确的控制器中,它应该在控制器收藏夹中,在def #create中,对不起,我是一个初学者,不管怎么说,它太棒了!
另外,我有一个更好的建议,那就是使用最喜欢的参数(在favorite controller #create中):
@favorite = Favorite.new(favorite_internship_id: params[:internship_id], favorite_user_id: current_user.id)我删除了另一行,它工作得很好!
https://stackoverflow.com/questions/61632547
复制相似问题