【发布时间】:2014-05-29 01:55:28
【问题描述】:
用户已获得授权并想要创建评论。创建新帖子时,有一个包含一个字段的表单:post。另一个字段是隐藏的(它在模型 Comment.rb 中)。如何在下面的def中分配用户的id,以便评论文本和user_id都保存?
评论/查看
<%= simple_form_for(@comment) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :user_id %> (this line should hide and id should assign itself)
<%= f.input :text %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
会话。控制器
def create
user = User.find_by_name(params[:name])
if user and user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to admin_url
else
redirect_to login_url, alert: "Неправильный логин или пароль!"
end
end
Comments_controller
def create
@user = User.all
@comment = Comment.all
@comment = Comment.new(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
【问题讨论】:
-
嘿,您应该删除 cmets_controller 的创建操作中的
@comment = Comment.all行,因为它会检索所有 cmets,但您在这里不需要它;)
标签: ruby-on-rails ruby-on-rails-4