【问题标题】:pass variables to controll and save to database将变量传递给控制并保存到数据库
【发布时间】:2013-05-10 17:59:41
【问题描述】:

我可以将变量传递给控制器​​,但我认为我的方法不正确。我有可以将回复应用于推荐的推荐,在我将回复嵌套在推荐中的路由中。

我试图将 user.id 和 refer.id 传递给回复控制器并将其写入数据库。 User.id 正在写入,但我无法让两个变量都进入数据库。

我检查了两个变量都进入了控制器,我只是没有正确执行方法。我尝试了很多组合,但我很困惑。

回复控制器

  class RepliesController < ApplicationController
     def new
      @user_id = params[:user_id]
      @user_id.to_s
      @reply = Reply.new
      @referral = Referral.find(params[:referral_id])
      @reply = @referral.replies.build(@user_id, :referral_id)
      respond_to do |format|
        if @reply.save
          format.html { redirect_to referrals_path, notice: 'Replied' }
        else
          format.json { render json: @reply.errors, status: :unprocessable_entity }
        end
      end
    end
  end

路线

    resources :referrals do
      resources :replies
    end

回复推荐的按钮 这是在索引页面上填充引荐的部分

  = link_to '<i class="icon-ok"> Reply</i>'.html_safe, new_referral_reply_path(:referral_id => referral.id, :replier_id => current_user.id)

试图为“posts”类型的方法实现“likes”,但在回复表中具有用户的 id 和推荐。基本上我需要将两个参数从链接传递到数据库中

现在我在 (http:// local host :3000/referrals/1/replies/new?user_id=2) 上收到此错误

RepliesController 中的 NoMethodError#new

“2”的未定义方法“stringify_keys”:字符串 Rails.root:/Users/laszlo/Documents/rails_projects/GemPort

应用程序跟踪 |框架跟踪 |全跟踪 app/controllers/replies_controller.rb:7:in `new'

【问题讨论】:

  • 看起来像一个嵌套资源。也许这对你有帮助:stackoverflow.com/questions/3784183/…
  • 您对params[@referral] 有什么期望?还有current_user.replies.new当然应该是current_user.replies.build
  • 我正在考虑做这样的事情@referral = Referral.find(params[:referral_id], params[:replier_id]) @reply = @referral.replies.build(params[@referral])
  • 链接中的参数以哈希的形式出现,对吗?如何通过 .new 或 .create 传递哈希?

标签: ruby-on-rails devise haml


【解决方案1】:

发现在写入数据库时​​将参数传递到列中很容易:

回复控制器:

  class RepliesController < ApplicationController
     def new
      @referral = Referral.find(params[:referral_id])
      @reply = @referral.replies.new(:user_id => params[:user_id], :referral_id => params[:referral_id])
      respond_to do |format|
        if @reply.save
          format.html { redirect_to referrals_path, notice: 'Replied' }
        else
          format.json { render json: @reply.errors, status: :unprocessable_entity }
        end
      end
    end
  end

这个链接帮助了我: undefined method `stringify_keys!' ruby on rails

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多