找不到任何接近我想要做的事情。我想將一個對象存儲到用戶的列中。該列是處於陣列的形式:將一個對象轉換爲散列,然後將其保存到用戶列
#postgres
def change
add_column :users, :interest, :string, array: true, default: '{}'
end
我有稱爲FooBar的設置用於其它用途的另一模型。每個用戶都有獨特的信息,因爲我添加了user_id
密鑰。
我試着去更有意義:
def interest
@user = User.find(current_user.id) # I need the logged in user's id
@support = Support.find(params[:id]) # I need the post's id they are on
u = FooBar.new
u.user_id = @user
u.support_id = @support
u.save # This saves a new Foo object..this is what I want
@user.interest.push(FooBar.find(@user)) # This just stores the object name itself ;)
end
所以,當我打電話u1 = FooBar.find(1)
我得到的哈希值回報。我想要當我說u1.interest
我得到相同的。原因是,我需要針對用戶上的那些鍵,即:u1.interest[0].support_id
這可能嗎?我查看了我的基本ruby文檔,沒有任何作品。哦..如果我通過FooBar.find(@user).inspect
我得到的散列,但不是我想要的方式。
我試圖做類似於stripe。看看他們的data
鍵。這是一個散列。
編輯豐富的回答:
我已,從字面上看,一個模式叫UserInterestSent
模型和表:
class UserInterestSent < ActiveRecord::Base
belongs_to :user
belongs_to :support # you can call this post
end
class CreateUserInterestSents < ActiveRecord::Migration
def change
create_table :user_interest_sents do |t|
t.integer :user_id # user's unique id to associate with post (support)
t.integer :interest_sent, :default => 0 # this will manually set to 1
t.integer :support_id, :default => 0 # id of the post they're on
t.timestamps # I need the time it was sent/requested for each user
end
end
end
我打電話interest
interest_already_sent
:
supports_controller.rb:
def interest_already_sent
support = Support.find(params[:id])
u = UserInterestSent.new(
{
'interest_sent' => 1, # they can only send one per support (post)
'user_id' => current_user.id, # here I add the current user
'support_id' => support.id, # and the post id they're on
})
current_user.interest << u # somewhere this inserts twice with different timestamps
end
而且interest
不利益,柱:
class AddInterestToUsers < ActiveRecord::Migration
def change
add_column :users, :interest, :text
end
end
你試圖使用'.to_json'的對象和保存的? – martincarlin87
@ martincarlin87是的,但我不能讓任何按鍵,即'u1.interest [0 ] .support_i d' – Sylar
@Sylar你能否解釋爲什麼你不使用常規的外鍵關係(例如, foobar_id作爲用戶模型中的字段)?或者,如果你需要保留Foobar的狀態,你可以有一個名爲UserFooBar的子類,它存儲的數據與沒有更新時一樣。 –