由于某种原因,当我点击“加入”(下面)时,会员资格模型不会被创建。相反,它只是移动到会员资格中的index.html.erb,其他什么都没有发生。我可能做错了什么?我真的很感激帮助。终端中的错误消息(不是真正的错误)在底部。
Places index.html.erb:
<% @places.each do |p| %>
<%= p.name %>
<%= link_to "Join", memberships_path(place_id: p.id, user_id: current_user.id, 'membership[place_id]': true), data: { turbo_method: "post" }, class:'', style:'' %>
<% end %>
会员控制器:
def create
@membership = Membership.new(membership_params)
if @membership.save
flash[:notice] = ""
redirect_back fallback_location: places_path
else
flash[:error] = "Unable to add membership."
redirect_back fallback_location: places_path
end
end
def membership_params
params.require(:membership).permit(place_id: params[:place_id], user_id: current_user.id )
end
Membership.rb:
class Membership < ApplicationRecord
belongs_to :user
belongs_to :place
end
Place.rb:
class Place < ApplicationRecord
belongs_to :user
has_many :memberships
has_many :users, through: :memberships
end
User.rb:
class User < ApplicationRecord
has_many :memberships
has_many :places, through: :memberships
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
路线:
resources :places
resources :users
resources :memberships
resources :places do
resources :memberships
end
resources :users do
resources :memberships
end
终端消息:
Started POST "/memberships" for 127.0.0.1 at 2023-04-18 17:32:54 -0400
Processing by MembershipsController#create as TURBO_STREAM
Parameters: {"membership"=>{"place_id"=>"true"}, "place_id"=>"1", "user_id"=>"1"}
Place Load (0.2ms) SELECT "places".* FROM "places" WHERE "places"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/memberships_controller.rb:13:in `create'
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/memberships_controller.rb:15:in `create'
TRANSACTION (0.1ms) BEGIN
↳ app/controllers/memberships_controller.rb:16:in `create'
Place Load (0.1ms) SELECT "places".* FROM "places" WHERE "places"."id" = $1 LIMIT $2 [["id", 0], ["LIMIT", 1]]
↳ app/controllers/memberships_controller.rb:16:in `create'
TRANSACTION (0.1ms) ROLLBACK
↳ app/controllers/memberships_controller.rb:16:in `create'
Redirected to http://127.0.0.1:3000/
1条答案
按热度按时间unguejic1#
因为在您的例子中,
permit
的参数应该只是一个键列表,而不是一个散列。并且您请求的参数没有嵌套在:membership
键下面,而是直接嵌套在参数的根目录中。更改到
此外:出于安全原因,我建议不要像这样将current_user的id传递给控制器,因为人们可能会更改这些值。
相反,我建议将强参数改为:
create
方法然后你的JavaScript设置似乎有问题,因为即使使用
data_method: :post
,请求仍然被识别为get
。我建议看看官方Rails指南中的Working with JavaScript in Rails并修复设置。