从反应组件传递参数值

时间:2015-12-06 23:22:09

标签: ruby-on-rails ruby reactjs react-rails

在我的应用中,人们可以评论宠物'图片。我正在使用here中的反应示例,​​尽管我改变了很多东西。

目前,它已成功显示现有评论。现在,当用户创建评论时,我必须传递评论正文,用户ID和宠物ID。我试图做以下事情:

var CommentForm = React.createClass({
handleSubmit:function()
    {
      var user=this.refs.user_id.getDOMNode().value.trim();
      var comment=this.refs.body.getDOMNode().value.trim();
      var pet_id=this.refs.pet_id.getDOMNode().value.trim();

      this.props.onCommentSubmit({comment:comment, user:user, pet:pet_id});
      if(!user||!comment||!pet_id)
        return false;
      var formData = $( this.refs.form.getDOMNode() ).serialize();
      this.props.onCommentSubmit( formData, this.props.form.action );

      // reset form
      this.refs.body.getDOMNode().value = "";
    },

render: function () {
return (
  <form ref="form" className="comment-form" action={ this.props.form.action } accept-charset="UTF-8" method="post" onSubmit={ this.handleSubmit }>
    <p><input type="hidden" name={ this.props.form.csrf_param } value={ this.props.form.csrf_token } /></p>
    <p><input type="hidden" ref="user" value={ this.props.user_id } /></p>
    <p><input type="hidden" ref="pet_id" value={ this.props.pet_id } /></p>
    <p><textarea ref="body" name="comment[text]" placeholder="Say something..." /></p>
    <p><button type="submit">Post comment</button></p>
  </form>
)
}
});

显然,它看起来并没有正确传递pet_id,因为我收到了错误消息

ActiveRecord::RecordNotFound in CommentsController#create
Couldn't find Pet with 'id'=

我的CommentsController看起来像

def create
    @pet = Pet.find(params[:pet_id])
    @comment = @pet.comments.new(comment_params)
    @comment.user = current_user

为了进一步说明,我有三个模型,Pets,Users和Comments,当用户发表评论时,评论会获得user_id,pet_id作为参数。

编辑:

我的反应组件看起来像

 <%= react_component('CommentBox', 
{:presenter => @presenter.to_json}, 
{:prerender => true}) %>

我的PetController看起来像

def show
    @comments = @pet.comments
    @user = current_user
    @presenter = {
        :comments => @comments,
        :user => current_user,
        :pet_id => @pet,
        :form => {
            :action => comments_path,
            :csrf_param => request_forgery_protection_token,
            :csrf_token => form_authenticity_token
      }

1 个答案:

答案 0 :(得分:0)

所以我可以看到一些问题。首先你使用ref你应该在哪里命名。

<input type="hidden" ref="pet_id" value={ this.props.pet_id } />

应该是

 <input type="hidden" name="pet_id" value={ this.props.pet_id } />

您同时设置操作和onSubmit。有理由这样做吗?为什么不在执行ajax请求时从道具中读取它?这很可能导致您的表单被提交,浏览器加载另一个页面。表单提交与服务器上的内容无关。问题出在您的客户端代码中。

我还会考虑将您的模型值放入自己的数组中。这通常是rails希望从服务器返回的内容。在您的情况下,它应该是params[:pet][:id]而不是params[:pet_id]。然后可以直接调用许多rails活动记录方法(如更新属性),从而减少冗长的代码。

@pet = Pet.find(params[:pet][:id])
@pet.update_attributes(prams[:pet])
@pet.save
相关问题