简体   繁体   English

在Ruby on Rails中推送到数组

[英]Pushing to an Array in Ruby on Rails

I am trying to create a string array inside my model, where I can push new strings (IDs) into the string array - but it's not pushing the correct values. 我正在尝试在模型中创建一个字符串数组,在这里我可以将新的字符串(ID)推送到字符串数组中-但它没有推送正确的值。

Here is how the model looks: 这是模型的外观:

class CreateCompanies < ActiveRecord::Migration
  def change
  create_table :companies do |t|

  t.string :name
  t.string :email
  t.string :users, array: true, default: []
  t.timestamps null: false
  end
 end
end

And here is how I'm adding the new values to the array in the Controller: 这是我将新值添加到Controller中的数组的方式:

c = Company.new
c.users << @user.id
c.save

A value does indeed get added to the array, but it's not the ID but just some random value like this: 确实确实将一个值添加到了数组中,但这不是ID,而是一些随机值,例如:

users: "--- []\n\u{478A6}"

Been stuck at this for a couple of days now - does anyone know what I'm missing? 现在被困了几天-有人知道我在想什么吗?

UPDATE: Added the code where I create a new Company 更新:添加了我创建新公司的代码

 def create
@user = User.new(user_params)
if @user.save

  @user.id = SecureRandom.random_number(999999)
  session[:user_id] = @user.id

  c = Company.new
  c.id = SecureRandom.random_number(999999)
  c.name = @user.company_name
  c.email = "email goes here"
  c.users << @user.id
  c.save

  @user.company_id = c.id
  @user.save

  redirect_to '/dashboard'
else
  redirect_to '/'
end
end

If you're trying to build a one-to-many relationship, what you should do is add a company_id field to the users table, add belongs_to :company to your app/models/user.rb and add has_many :users to your app/models/company.rb . 如果您尝试建立一对多关系,则应该在users表中添加一个company_id字段,将belongs_to :company添加到您的app/models/user.rb并将has_many :users添加到您的app/models/company.rb

Then you'd be able to access the users just like you need. 然后,您将可以根据需要访问用户。

UPDATE UPDATE

If you want to create a company with the user you can just go like this. 如果要与用户创建公司,您可以像这样去。

@user.company = Company.create name: 'Some name'

Or even better to avoid duplication. 甚至最好避免重复。

@user.company = Company.find_or_create_by name: 'Some name'

I wonder if here you want to build many to many relationship, the best way to do this is using a many to many table instead of store all ids as an array string in databases; 我想知道您是否要建立多对多关系,最好的方法是使用多对多表,而不是将所有id作为数组字符串存储在数据库中。

If you do want to store like this, the best way should be form a string instead of put array directly. 如果确实要这样存储,最好的方法应该是形成一个字符串而不是直接放置数组。 For this things like array.join() would be very helpful for you. 为此,例如array.join()对您将非常有帮助。

If you still insist your way, maybe you should try array.push() instead of << 如果您仍然坚持自己的方式,也许您应该尝试使用array.push()代替<<

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM