连接 Rails api 关联 Ember
Connecting Rails api association with Ember
我有两个模型:user
和 card
。
当用户创建新卡时,我想将用户与该卡相关联。 (你可以假设 user_id
是 1)
对于Rails部分,
card.rb
class Card < ActiveRecord::Base
has_and_belongs_to_many :users
end
user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :cards
end
对于Ember部分,
app/routes/card/new.js
actions: {
save(title, description) {
let user = this.get('store').find('user', 1);
const newCard = this.get('store').createRecord('card', {
title,
description,
user
});
newCard.save().then((card) => {
// go to the new item's route after creating it.
this.transitionTo('card.card', card);
});
}
}
目前,我可以通过Rails控制台将它们关联起来。我想知道如何通过 Rails api 和 Ember 数据关联它们,以便在我创建新的 card
时关联 current user
连同 card
.
回购 link (Rails): https://github.com/ghoshnirmalya/hub-server
回购 link (Ember): https://github.com/ghoshnirmalya/hub-client
您需要更新控制器中的代码:
https://github.com/ghoshnirmalya/hub-server/blob/master/app/controllers/cards_controller.rb
在您的 create
方法中,您需要获取收到的用户 ID 并建立连接。
编辑:
def create
@card = Card.new(card_params)
if @card.save
@card.users << User.find(params[:data][:attributes][:user_id]) if params[:data][:attributes][:user_id] # this is my guess
render json: @card
else
render json: @card, :status => 422
end
end
我有两个模型:user
和 card
。
当用户创建新卡时,我想将用户与该卡相关联。 (你可以假设 user_id
是 1)
对于Rails部分,
card.rb
class Card < ActiveRecord::Base
has_and_belongs_to_many :users
end
user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :cards
end
对于Ember部分,
app/routes/card/new.js
actions: {
save(title, description) {
let user = this.get('store').find('user', 1);
const newCard = this.get('store').createRecord('card', {
title,
description,
user
});
newCard.save().then((card) => {
// go to the new item's route after creating it.
this.transitionTo('card.card', card);
});
}
}
目前,我可以通过Rails控制台将它们关联起来。我想知道如何通过 Rails api 和 Ember 数据关联它们,以便在我创建新的 card
时关联 current user
连同 card
.
回购 link (Rails): https://github.com/ghoshnirmalya/hub-server
回购 link (Ember): https://github.com/ghoshnirmalya/hub-client
您需要更新控制器中的代码:
https://github.com/ghoshnirmalya/hub-server/blob/master/app/controllers/cards_controller.rb
在您的 create
方法中,您需要获取收到的用户 ID 并建立连接。
编辑:
def create
@card = Card.new(card_params)
if @card.save
@card.users << User.find(params[:data][:attributes][:user_id]) if params[:data][:attributes][:user_id] # this is my guess
render json: @card
else
render json: @card, :status => 422
end
end