Ember:如何使用Rails API创建连接表模型

时间:2018-04-04 15:50:54

标签: ember-data rails-api

我正在使用Rails5 API和Ember 3。 在Rails端,我想保存的模型定义如下:

class ShopLanguage < ApplicationRecord
  belongs_to :shop
  belongs_to :language
end

这是Shop模型:

class Shop < ApplicationRecord
  has_many :shop_languages, inverse_of: :shop, dependent: :destroy
  has_many :languages, through: :shop_languages
end

这是ShopLanguage序列化程序:

class ShopLanguageSerializer < ActiveModel::Serializer
  attributes :id, :shop_id, :language_id, :modified_by
  belongs_to :shop
  belongs_to :language
end

问题在于,当我尝试为Ember的指定商店创建新的shop_language时:

# controllers/shop-languages.js
actions: {
  saveLanguage(aLanguage) {
  let shopLanguage = this.store.createRecord('shop-language', {
         language: aLanguage,
         shop: this.get('currentShop.shop'),
         modifiedBy: this.get('currentUser.user').get('username')
       });
  shopLanguage.save().then(function() {
          this.get('flashMessages').info('New language added with success');
      });

language_id未在Rails端params的{​​{1}}哈希中传入:

ShopLanguagesController

当我检查Ember应用程序点击的URL时,似乎没问题:

# shop_langauges_controller.rb
class ShopLanguagesController < ApplicationController
  before_action :find_shop
  before_action :find_language, only: [:create, :destroy]

  def create
    @shop.languages << @language
    json_response(@shop.languages, :created)
  end

  private

  def language_params
    params.permit(:language_id, :shop_id, :id, :modified_by)
  end

  def find_shop
    @shop = Shop.find(params[:shop_id])
  end

  def find_language
    @language = Language.find_by!(id: params[:language_id])
  end
end

错误来自POST http://localhost:4200/shops/613/languages 方法,因为find_language为空。 为什么这样 ?这有什么问题?谢谢

0 个答案:

没有答案