我正在尝试将 user_id(以便我可以访问用户详细信息)附加到已附加到名为 Park 的页面的评论中。
我设置了三个表:Park、Comment 和 User:
class Park < ActiveRecord::Base
has_many :comments
has_many :users
end
class Comment < ActiveRecord::Base
belongs_to :park
has_one :user
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments
validates_presence_of :username
validates :username, uniqueness: true
def admin?
admin
end
end
正如您在上面看到的,我使用 Devise gem 进行用户和授权。
评论显示在 Park 上,因此它们是嵌套的:
park_comment GET /parks/:park_id/comments/:id(.:format) comments#show
我的评论 Controller 设置如下:
class CommentsController < ApplicationController
before_action :authenticate_user!, only: [:create]
before_action :authorize_admin!, only: [:delete]
def create
@park = Park.find(params[:park_id])
@comment = @park.comments.create(comment_params)
redirect_to park_path(@park)
end
def destroy
@park = Park.find(params[:park_id])
@comment = @park.comments.find(params[:id])
@comment.destroy
redirect_to park_path(@park)
end
private
def comment_params
params.require(:comment).permit(:comment, :user_id, :park_id)
end
end
我已经能够从 park_id 切换到 user_id,但代价始终是在另一项上收到一个大的 nil。
我只是尝试在我的评论表单中添加隐藏字段
<%= form_for([@park, @park.comments.build]) do |f| %>
<p>
<%= f.label :comment %><br>
<%= f.text_area :comment %>
<%= hidden_field_tag(:user_id, current_user.id) %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
但这似乎没有产生任何结果。
我尝试过一些 ActiveRecord 加入工作,但它不想锁定我的创建,所以我放弃了。现在已经在这方面花费了一段时间,我确信有一个我只是没有看到的简单解决方案。有想法吗?
最佳答案
您的hidden_field_tag
不起作用。它将创建一个单独的参数,而不是嵌套在您想要的参数键下的参数。
我的建议是完全删除hidden_field并在 Controller 中指定current_user。
class CommentsController < ApplicationController
def create
@park = Park.find(params[:park_id])
@comment = @park.
comments.
create(
comment_params.
merge(user_id: current_user.id) # adding here, on creation
# or merge(user: current_user)
)
redirect_to park_path(@park)
end
def comment_params
params.
require(:comment).
permit(:comment)
end
end
为什么?因为否则用户可能会更改该隐藏字段的值,并且您将错误地存储评论的 user_id 值。
关于mysql - 使用另一个表中的 ID 创建新表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671261/