0

我有一个与 rails API 一起运行的 rails 应用程序,在 config/initializers/constants.rb 中有一个 DAYS_LIMIT 的常量值

DAYS_LIMIT = 40
DEFAULT_PRICE = 1.29

但现在在应用程序中,我添加了一个输入字段,以便用户决定他的 DAYS_LIMIT。所以我想从 API 模型内部的数据库中获取该值。

我已经放置了断点,可以看到在 API 控制器内部,数据是从应用程序传输的,而不是模型。

作为请求的问题进行编辑,它是一个 React-on-Rails 应用程序,这是将新输入字段保存到数据库的代码(我已删除其他字段,因此问题看起来更短)

export const saveChannel = (files) => {
    return async (dispatch, getState) => {
        const { channel } = getState();
        const {rss_podcast_days} = channel;
        const { image } = files;

    const save = id ? updateChannel : createChannel;

    const sub_required = subscription_required !== undefined ? subscription_required : false;

        const formData = new FormData();
                formData.append('channel[rss_podcast_days]', rss_podcast_days || '');


    if (Object.keys(image).length) {
      formData.append('channel[image]', image);
    }

    const channelId = await dispatch(save(formData, id));

    dispatch(fetchChannel(id));

    return id;
  };
};

从应用程序控制器

podcast_list = RestClient.get("#{ENV['URL_API']}/api/#{@channel.id.as_json}/podcast/list")
      @podcasts = JSON.parse(podcast_list.body)
      @podcasts = @podcasts.sort.reverse.to_h

这是来自 API 控制器,数据是从应用程序传输的

def index
    podcasts = @channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in])

    render json: Podcasts::Normalizer.normalize(podcasts, @channel.station.default_podcast_price)
  end

在这里,我想从 API 模型中获取数据而不是常量。

scope :by_days_limit, -> {with_tags.more_recent_than(Date.today - DAYS_LIMIT.days).ordered}

它应该用今天的日期减去用户输入的值(DAYS_LIMIT),但现在我得到undefined local variable or method如果我尝试直接获取

4

2 回答 2

0

兄弟,如果您的类有常量,例如DAYS_LIMIT您可以使用该类本身访问它,

class Demo
  DAYS_LIMIT = 5
end

Demo.DAYS_LIMIT您可以通过在控制器中或任何您需要的地方访问该常量。

祝你好运!

于 2019-04-04T09:16:30.247 回答
0

好的,所以我终于明白了,我不知道我是否应该删除这个线程或只是告诉我是如何做到的。如果不恰当,请告诉我,我将删除整个线程。

所以这就是我的做法,在 API 控制器中我必须添加我的 fetch 以便参数(列表)知道我在说什么。@channel.days_limit

def index
    podcasts = @channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in], @channel.days_limit)

    render json: Podcasts::Normalizer.normalize(podcasts, @channel.station.default_podcast_price)
end

然后在模型的 def 列表中,我添加了 days_limit 有参数

def list(page = nil, nb_items_per_page = 40, ordered_in = 'desc', days_limit)
      ordered_in = ordered_in.in?(['asc', 'desc']) ? ordered_in : 'desc'
      page.blank? ? by_days_limit(days_limit) : by_page(page, nb_items_per_page, ordered_in)
end

最后在模型的范围内,我传入了新的论点

scope :by_days_limit, -> (days_limit) {with_tags.more_recent_than(Date.today - days_limit.days).ordered}

现在来自应用程序的用户输入通过控制器传递给模型。

于 2019-04-04T14:52:11.120 回答