我有一个与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
答案 0 :(得分:0)
如果您的类具有像DAYS_LIMIT
这样的常量,那么您可以使用该类本身来访问它,例如
class Demo
DAYS_LIMIT = 5
end
您可以通过控制器中的Demo.DAYS_LIMIT
或任何您需要的位置访问该常数。
祝你好运!
答案 1 :(得分:0)
好的,所以我终于明白了,我不知道该删除该线程还是告诉我如何做到这一点。如果不合适,请告诉我,我将删除整个线程。
这就是我的操作方式,在API控制器中,我必须添加我的提取内容,以便参数(列表)知道我在说什么。 import os
os.path.dirname(os.path.abspath(__file__))
@channel.days_limit
然后在模型的def列表中,我添加了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 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
现在,来自应用程序的用户输入正通过控制器传递给模型。