我有一个运行在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
发布于 2019-04-04 22:52:11
好了,我终于明白了,我不知道我是应该删除这个帖子,还是应该告诉你我是怎么做到的。如果不合适,请告诉我,我会删除整个帖子。
所以这就是我是如何做到的,在API控制器中,我必须添加我的fetch,以便参数(list)知道我在谈论什么。@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然后在模型的定义列表中,我添加了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-04 17:16:30
Bro如果你的类有像DAYS_LIMIT这样的常量,你可以使用那个类本身来访问它,例如,
class Demo
DAYS_LIMIT = 5
end您可以在控制器中或任何需要的地方通过Demo.DAYS_LIMIT访问该常量。
祝好运!
https://stackoverflow.com/questions/55502805
复制相似问题