如果这篇文章的标题不清楚,我提前道歉,我很难解释我遇到的问题。我有一个允许用户创建目标的应用程序。我正在尝试创建一个Collaboration模型,以便用户可以彼此分享他们的目标。为此,我创建了一个属于用户和目标模型的协作模型,并存储了goal_id和user_id,以表示用户对其他目标的访问权限。
我在Goal#show中创建了一个表单,允许用户输入他们想要与之共享的用户的电子邮件地址。我将使用该电子邮件,从相关记录中获取user_id并创建Collaboration记录条目。我无法从获取用户电子邮件到获取ID并将其作为Param传递。代码发布在下面。
CollaborationsController.rb
class CollaborationsController < ApplicationController
def create
@goal = Goal.find(params[:goal_id])
@user = User.find_by(email: params[:email])
#@user=User.find(params[:email])
if @user
@collaboration = @goal.collaborations.create(collaboration_params)
if @collaboration.save
flash[:notice] = "User successfully added to goal."
else
flash[:error] = "There was a problem adding user. Please try again."
end
else
flash[:error] = "Sorry that wasn't a valid username. Please try again."
end
redirect_to goal_path(@goal)
end
def collaboration_params
params.require(:collaboration).permit(:user_id, :goal_id)
end
end
协作/ _form.html.erb
<%= form_with(model: [ @goal, @goal.collaborations.build ], local: true) do |form| %>
<p>
<%= form.label :email %>
<%= form.text_field :email %>
</p>
<p>
<%= form.submit %>
<p>
<% end %>
开发者工具中的表单数据:
utf8: ✓
authenticity_token: RXa9u10cLdw1FK29hOly33wWDN+dDd5NTtvZ/yYbKfMJ6RhHw+nV8/OgiFbQ+raRcNzbbWItCct7lv+A3CmINw==
collaboration[email]: [actualemailofuser]
commit: Create Collaboration
提交并处理电子邮件地址。如何从找到包含该电子邮件的用户记录到从该记录获取user_id以将其作为参数提交?
答案 0 :(得分:0)
出现此问题是因为我没有成功将:email参数传递给Controller方法创建。
以下是工作代码:
collaborations_controller.rb
class CollaborationsController < ApplicationController
def create
@goal = Goal.find(params[:goal_id])
@user = User.find_by(email: params[:email])
if @user
@collaboration = Collaboration.new(goal_id: @goal.id, user_id: @user.id)
if @collaboration.save
flash[:notice] = "User successfully added to goal."
else
flash[:error] = "There was a problem adding user. Please try again."
end
else
flash[:error] = "Sorry that wasn't a valid username. Please try again."
end
redirect_to goal_path(@goal)
end
def collaboration_params
params.require(:collaboration).permit(:user_id, :goal_id, :email)
end
end
合作/ _form.html.erb
<%= form_with(model: [ @goal, @goal.collaborations.build ], local: true) do |form| %>
<p>
<%= text_field_tag :email, params[:email] %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>