【问题标题】:How can I make the id field be hidden and assign itself?如何使 id 字段隐藏并自行分配?
【发布时间】: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


【解决方案1】:

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 cmets。

【讨论】:

  • Joe Pym 给您的提示:在编辑答案时,您可以选择代码段并使用 ctrl+k 将其格式化为代码块
  • @MrYoshiji - 谢谢。这是一个很棒的提示。
  • 未定义的局部变量或方法`current_user'
  • 请帮帮我!未定义的局部变量或方法`current_user'
  • 猫 - 我更新了。您通常希望将 User.find(session[:user_id]) 作为 ApplicationController 上 current_user 方法的一部分,以更好地处理登录用户。
【解决方案2】:

您可以通过这样做来隐藏该字段

<%=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 %>

【讨论】:

    猜你喜欢
    • 2019-03-26
    • 2012-05-06
    • 2016-08-24
    • 1970-01-01
    • 2012-02-18
    • 2013-04-06
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多