用户已获得授权,并且想要创建评论。创建新帖子时,表单中包含一个字段: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
答案 0 :(得分:2)
将user_id
退出表单。相反,在控制器中,写:
def create
@user = User.find(session[:user_id]) #whoever the logged in user is
@comment = @user.comments.build(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
另外,请确保您的用户对has_many
评论进行了建模。
答案 1 :(得分:0)
您只需执行此操作即可隐藏字段
<%=f.hidden_field :user_id, :value => "its_value" %>
所以它会像
<%= simple_form_for(@comment) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.hidden_field :user_id , :value => @user.id %>
<%= f.input :text %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>