创建自定义rails路由:未定义方法`+ @'表示“10”:字符串

时间:2015-01-25 02:31:04

标签: ruby-on-rails routes

我正在制作自定义rails路线:

match '/setFavoriteRestaurant/:user_id/:restaurant_id/:campaignSetFav_id/:metro_id/:time_period', to: 'requests#setFavoriteRestaurant', via: 'get'

控制器操作:

def setFavoriteRestaurant
        setFavorite = "INSERT INTO androidchatterdatabase.users_favorite_restaurants(usersId,restaurantId,campaignIdSetFav,metroId,timePeriod,favoritedDt)
                       VALUES(" + params[:user_id].to_s + "," 
                                + params[:restaurant_id].to_s + "," 
                                + params[:campaignSetFav_id].to_s + ","
                                + params[:metro_id].to_s + ","
                                + params[:time_period].to_s + ",
                                NOW());"

        ActiveRecord::Base.connection.execute(setFavorite)
    end

然而,在浏览器中使用http://localhost:3000/setFavoriteRestaurant/1/2/3/5/4

进行测试时

它返回一个奇怪的错误:undefined method +@' for "2":String

为什么在其他方法设置完全相同的情况下才能运行?

2 个答案:

答案 0 :(得分:1)

这与你如何分解线条有关。 Ruby不知道VALUES(" +行和+ params[:restaurant_id]是同一件事的一部分。这是因为VALUES( +行已完成。将+移动到行尾,以便Ruby知道期望下一行是延续。

setFavorite = "INSERT INTO androidchatterdatabase.users_favorite_restaurants(usersId,restaurantId,campaignIdSetFav,metroId,timePeriod,favoritedDt)" + 
                      "VALUES(" + params[:user_id].to_s + "," +
                      params[:restaurant_id].to_s + "," +
                      params[:campaignSetFav_id].to_s + "," +
                      params[:metro_id].to_s + "," +
                      params[:time_period].to_s + ",NOW());"

另外,请注意我移动了一些其他东西以避免新行和额外空格。

我不确定你为什么喜欢这里的原始SQL,但你应该考虑通过Rails。好像你正在打开SQL注入。至少,您可以在路由中使用一些约束来仅匹配整数。

答案 1 :(得分:0)

Ruby有几种引用多行字符串的方法:

1)这是ruby的heredoc语法:

def some_action

  setFavorite = <<-"END_OF_INSERT"
    INSERT INTO androidchatterdatabase.users_favorite_restaurants(
      usersId,
      restaurantId,
      campaignIdSetFav,
      metroId,
      timePeriod,
      favoritedDt
    )
    VALUES( 
      "#{params[:user_id]}",  
      "#{params[:restaurant_id]}",
      "#{params[:campaignSetFav_id]}",
      "#{params[:metro_id]}",
      "#{params[:time_period]}",
      NOW()
    );
  END_OF_INSERT

end

说明:

setFavorite = <<-"END_OF_INSERT"

-   =>  Terminator does not have to be at the start of the line.
""  =>  This is a double quoted string--do interpolation.

2)这里是%Q{}

  setFavorite = %Q{
    INSERT INTO androidchatterdatabase.users_favorite_restaurants(
      usersId,
      restaurantId,
      campaignIdSetFav,
      metroId,
      timePeriod,
      favoritedDt
    )
    VALUES( 
      "#{params[:user_id]}",  
      "#{params[:restaurant_id]}",
      "#{params[:campaignSetFav_id]}",
      "#{params[:metro_id]}",
      "#{params[:time_period]}",
      NOW()
    );
  }

但是,您的SQL语句仍然容易受到SQL注入攻击。检查数据库适配器以了解如何进行参数替换。