【问题标题】:Pass value via hidden_field in rails通过 rails 中的 hidden_​​field 传递值
【发布时间】:2013-02-20 13:09:58
【问题描述】:

我正在尝试在我的应用程序中实现评级系统,我尝试了 Rateit 但无法让它工作,所以我想我会尝试构建自己的,而且我希望通过了解这个过程来了解更多信息

目前我正在尝试传递点击星的值

表格

<%= form_for @rating do |f| %>
  <%= f.hidden_field :ratings, :id => "hiddenRating", :value => '' %>
  <%= f.hidden_field :user_id, :value => current_user.id %>
  <%= f.hidden_field :recipe_id, :value => @recipe.id %>
  <div class="ratings">
    <ul>
      <li id="firstStar"></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <%= f.submit "Submit" %>
<% end %>

JS

$(document).ready(function(){
  $('#firstStar').click(function(){
    $('#hiddenRating').value = 1;
  });
}); 

所以这个想法是,如果用户点击第一个星,那么值 1 应该作为表单中的评级值传递,这不会发生,因为我不知道在其中传递什么

:value => ''

我确信有更好的方法可以做到这一点,但正如我所说,我想逐个学习,以便到最后我可以把它们放在一起,当然如果有人有更好的建议,请告诉我。

编辑

控制器

def new
  @rating = Rating.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @rating }
  end
end

def create
  @rating = Rating.new(params[:rating])

  respond_to do |format|
    if @rating.save
      format.html { redirect_to @rating, notice: 'Rating was successfully created.' }
      format.json { render json: @rating, status: :created, location: @rating }
    else
      format.html { render action: "new" }
      format.json { render json: @rating.errors, status: :unprocessable_entity }
    end
  end
end

【问题讨论】:

  • 好的,所以我刚刚尝试了这个 $('#hiddenRating').attr('value', 1);它有效,它发布了值 1
  • 我不确定你的控制器是什么样的,但不要忘记在那里验证用户 ID。不要依赖表单中的 user_id 是有效数据。可以伪造。
  • 我已经更新了我的控制器的问题,current_user.id 怎么可能是伪造的?
  • 一定要阅读这方面的一些指南:Rails GuideHealthy Skepticism
  • 最好的做法是验证 current_user.id 是否与会话中的 current_user.id 匹配

标签: javascript jquery ruby-on-rails ruby-on-rails-3


【解决方案1】:

好的,希望这可以帮助处于类似情况的其他人,我的表格现在看起来像这样

<%= f.hidden_field :ratings, :id => "hiddenRating"%>#Value has been removed

我的 Jquery 看起来像这样

$(document).ready(function(){
 $('#firstStar').click(function(){
  $('#hiddenRating').val(1);
 });
});

没有必要在表单中传递值,因为 .val() 将其分配给 id

这是我的理解

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多