Rails通过params

时间:2011-06-12 20:53:18

标签: ruby-on-rails arrays params

我觉得我错过了一种从根本上说更简单的方法;无论哪种方式,我似乎都没有数组的语法。试图把东西塞进params数组。任何帮助表示赞赏。

@user = User.find(params[:user][:id])

array_of_match_information = Array.new
array_of_match_information[mentee] = @user.id
array_of_match_information[mentor] = self.id
array_of_match_information[status] = "Pending"    

@match = Match.new(params[:array_of_match_information])

感谢。

3 个答案:

答案 0 :(得分:1)

array_of_match_information = Hash.new
array_of_match_information[:mentee] = @user.id
array_of_match_information[:mentor] = self.id
array_of_match_information[:status] = "Pending"    

修改

Hash是一个键/值存储,就像您打算这样做。

mentee是与值@user_id

相关联的键

数组不组织数据(除非您认为数组中的位置已知且有意义)

EDIT2:

并纠正这个:

@match = Match.new(array_of_match_information)

EDIT3:

我建议您查看http://railsforzombies.org,看来您需要一个好的教程。

实际上,在学习时构建应用程序可能会有危险,因为当您不了解基本体系结构时,最终会过度编码不可维护的代码。

例如,你的行:

    array_of_match_information[:mentor] = self.id

看起来很奇怪。

答案 1 :(得分:1)

看来,您正在尝试实现基本的社交网络功能。如果我是对的,你应该使用关联。它看起来像这样(我不知道你的导师 - 受指关系的细节,所以我认为这是一个多对多的关系):

class User < ActiveRecord::Base
    has_many :matches
  has_many :mentors, :through => :match
  has_many :mentees, :through => :match
end

class Match < ActiveRecord::Base
  belong_to :mentor, :class_name => 'User'
  belong_to :mentee, :class_name => 'User'
end

然后,在您的控制器中,您可以这样做:

class matches_controller < ApplicationController

  def create
    # current_user is a Devise helper method 
    # which simply returns the current_user through sessions. 
    # You can do it yourself.

    Match.create({ :mentee => @user, :mentor => current_user }) 
    # "pending" status could be set up as a default value in your DB migration
  end

end

但正如我所说,这只是一个代码示例。我不能保证它会起作用或适合您的应用程序。

你完全应该看看this book

答案 2 :(得分:0)

我不是100%确定你要做的是什么,但至少,你应该在设置3个值时使用符号:

array_of_match_information[:mentee] = @user.id
array_of_match_information[:mentor] = self.id
array_of_match_information[:status] = "Pending" 

编辑:

你应该这样做:

match_information = {}
match_information[:mentee] = @user.id
match_information[:mentor] = self.id
match_information[:status] = "Pending"

没有看到你的模型,我很难知道,但我怀疑它实际上想要哈希,而不是数组。