2015-12-29 87 views
0

我有一个朋友表,合并两个Rails模型

create_table "friendships", force: :cascade do |t| 
    t.integer "user_id" 
    t.integer "friend_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.string "name" 
end 

当用户添加好友的友谊模式创造了一个新的记录有唯一ID的user_id一个friend_idname值。

在我的角度应用程序,我有一个模板,重复每个friendship in friendships

这是JSON结果当朋友已经加入,

[{"id":17,"friend_id":3,"name":"Kees Keesen"}] 

的id是友谊的id和friend_id是朋友的实际用户ID。

所以我现在正在做的是复制我的数据。我有一个名称,电子邮件等用户模型。但是,当我添加一个朋友,我必须添加一个名称值(和更多)的友谊记录。

这是users.json JSON结果,

{"id":3,"email":"[email protected]","name":"Kees Keesen"} 

所以是有可能保持友谊unqique ID(我需要删除的友谊纪录),但做一个链接,用户模型所以我不必复制我的数据?

*更新*

这里是我的友谊控制器,

def index 
    friends = current_user.friendships.as_json 
    # friends = current_user.friends.as_json(:only => [:name, :email, :id]) 
    render :json => friends 
end 

我已经添加到了我的用户模型,

has_many :friendships 
has_many :friends, :through => :friendships 
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
has_many :inverse_friends, :through => :inverse_friendships, :source => :user 

这给我的友谊模式,

belongs_to :user 
belongs_to :friend, :class_name => "User" 

我已经移除的友谊表的名称列中,JSON输出,友谊是现在,

[{"id":2,"user_id":1,"friend_id":1,"created_at":"2015-12-29T19:24:28.788Z","updated_at":"2015-12-29T19:24:28.788Z"}] 

回答

0

在事物的角度侧,你应该做的方法通过ID,它访问获取用户幕后的缓存。然后,当你获得友谊时,用这种方法替换它们所代表的用户对象的id。如果用户已经被看到,那么你不需要再从服务器请求它。 JSON格式具有不能表示链接的缺点,所以我们倾向于使用ID来代替,并且只要我们获取对象就将它们变成链接。

1

这里幸福的方式是与自我指涉联想。

class User < ActiveRecord::Base  
    has_many :friendships 
    has_many :friends, :through => :friendships 
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
    has_many :inverse_friends, :through => :inverse_friendships, :source => :user 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, class_name: "User" 
end 

有了这个解决方案,你会得到的数据结构约束的唯一ID,您的用户user_id,并为友谊的倒数方面的friend_id,这两者指向User模型,以避免复制。这是一种很常见的做事方式。

这里有一个注释:inverse_friendships用于查询某个用户是由谁添加的,而不是他们自己添加的用户。

UPDATE

为了通过Friendship访问User信息,它可以委派属性要求:

class Friendship < ActiveRecord::Base 
    ... snip ... 

    delegate :name, :email, to: :friend 
end 

希望这有助于!

+0

感谢您的意见。我可能会错误地应用代码,但似乎没有改变。你会期望json是什么?另外,如果我在'友情“模型中注释掉代码,json仍然会呈现相同的效果,换句话说友情模型似乎没有做任何事情。我看到你从Railscast获得了代码。这也是我的向导。 –

+0

如果你的JSON根本没有改变,你应该重新启动一切。这是非常不同的代码;)最简单的事情是检查并确保您的JSON表示没有名称字段。 –

+0

嗯。我关闭了我的Rails服务器。从友谊表中删除了名称列,重新设置了我的数据库并重新调入,但仍然没有更改json输出。我已更新我的问题以反映更改。也许你可以发现我做错了什么?也许在控制器中。 –