@rubylang

Страница 980 из 1684
v
18.04.2017
11:48:11
тот же самый алгоритм

Sergey
18.04.2017
11:49:23
мне кажется главное — уметь кататься на гироскутере

Nursultan
18.04.2017
11:51:18
Anton
18.04.2017
12:34:36
А почему :desc, а не :asc? Item.order_by попробуй
спасибо за наводку на order_by(думаю, ты имелл ввиду sort_by). Получилось отсортировать во вьюхе таким способом <% @posts.sort_by { |post| post.impressionist_count }.reverse.first(10).each do post %> <%= link_to post.title, post %> <%= post.impressionist_count %> <% end %>

Google
Vitaly
18.04.2017
12:35:52
всем привет. скажите плиз, правда что с онлайн оплатой(типа оплата услуг через инет) очень много мороки? из-за налогов(всякой отчетности) и законов и что там постоянно они меняются.

Vasiliy
18.04.2017
12:47:12
и sort_by на сколько я знаю сортирует выходной массив, т.е. у тебя идёт запрос Post.all(или что там в @posts), это всё идёт в память, а потом уже сортируется и fisrt(10) выбирает уже 10 записей из массива всех постов твоих а не запросом LIMIT

а почему у тебя ордер не работает? Какой запрос к БД идёт?

как сам impression подключен? is_impressionable counter_cache: true, unique: :session_hash

Anton
18.04.2017
13:10:35
а почему у тебя ордер не работает? Какой запрос к БД идёт?
есть посты, которые выводятся на главную

def index @posts = storage.list_for(params[:page], params[:tag]) end

конкретный пост, на который ты при клике переходишь def show @post = storage.friendly.find(params[:id]) impressionist(@post) end

выборка идет из опубликованых постов def storage Post.published end

Vasiliy
18.04.2017
13:15:06
storage.order(impressions_count: :desc).first(10) <— тебе же по сути общее количество просмотренных надо

в консоли Post.published.order(impressions_count: :desc).first(10) верно выводит?

Google
Anton
18.04.2017
13:21:30
Vasiliy
18.04.2017
13:23:17
Post.published.order(impressions_count: :desc).first(10).map(&:impressions_count) а запрос какой?

Post Load (0.7ms) SELECT `posts`.* FROM `posts` ORDER BY `posts`.`impressions_count` DESC LIMIT 10

Anton
18.04.2017
13:25:07
Post Load (3.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."published" = $1 ORDER BY "posts"."impressions_count" DESC LIMIT $2 [["published", true], ["LIMIT", 10]] => [3, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Vasiliy
18.04.2017
13:36:49
верно же - 3,1,1

Anton
18.04.2017
13:43:04
как мне в этом методе прописать сортировку? def index @posts = storage.list_for(params[:page], params[:tag]) end

Vasiliy
18.04.2017
13:48:45
я чет хз что такое list_for но думаю storage.order(impressions_count: :desc).list_for...

Anton
18.04.2017
13:49:05
это для пагинации

и тегов

мне кажется я не очень понимаю, как счетчик работает, у меня у записи, которая имеет 59 кликов просмотров impressions_count: 3> и у записи, которая с 68 кликов просмотров тоже impressions_count: 3>,

Vasiliy
18.04.2017
14:07:12
там доки к нему почитай) ты как узнал что 59?

Anton
18.04.2017
14:07:15
короч отбой, impressions_count и impressionist_count - разные вещи, откуда берутся данные impressionist_count?

та читал...

я выводил сначала impressionist_count, он просто клики не уникальные считает,

Vasiliy
18.04.2017
14:08:29
http://rusrails.ru/active-record-associations#counter_cache

чтобы он пересчитал этот count надо просмотр добавить

т.е. он при изменении значения пересчитает счетчик, на основе , unique: :session_hash

т.е. уникальные сессии зачтет только

Anton
18.04.2017
14:11:15
т.е. он impressionist_count проводит через unique: :session_hash и выводит из них уникальные, это и есть impressions_count?

Vasiliy
18.04.2017
14:11:55
угу

Google
Vasiliy
18.04.2017
14:15:01
а без unique оно работает как-то как в доке написано(вроде уник по request_hash)

Anton
18.04.2017
14:16:29
спасибо помощь, где тут лайк поставить?)

Vasiliy
18.04.2017
14:19:10
да не за что, я помню тоже интегрировал его и такой - эээ, мне просто надо количество просмотров но по хорошему это так себе штука, для юзеров только чтобы видно было, для нормальных счетчиков надо метрику и аналитику

Akamit
18.04.2017
16:07:13
привет, есть пара моделей, примерно таких Person(string: snils, string: name) и Personnel(string: snils, string: manager_snils, string: addithional_info). никак не осилю как сделать has_many :subordinates through: :personnel для Person. В итоге сделал через метод Person: def subordinates Person.where(snils: Personnel.where(manager_snils: self.snils).pluck(:snils)) end подскажите пожалуйста как это сделать через has_many?

Vasiliy
18.04.2017
16:28:41
таки почитать доки немного

ту часть где про связи, ключи, миграции для связей

ojab
18.04.2017
16:48:20
привет, есть пара моделей, примерно таких Person(string: snils, string: name) и Personnel(string: snils, string: manager_snils, string: addithional_info). никак не осилю как сделать has_many :subordinates through: :personnel для Person. В итоге сделал через метод Person: def subordinates Person.where(snils: Personnel.where(manager_snils: self.snils).pluck(:snils)) end подскажите пожалуйста как это сделать через has_many?
Проект новый или legacy? Если новый — лучше переименовать snils в id (он в любом случае используется как id), personnel вообще можно убрать (судя по схеме вся информация вполне может храниться в person). Базово: Personnel belongs_to :manager, class_name: 'Person' Personnel has_one :subordinate, class_name: 'Person' Person has_many :personnels, inverse_of: :manager Person has_many :subordinates, through: :personnels + везде проставить нужные foreign_key и primary_key (см. http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)

Akamit
18.04.2017
17:00:15
Person.personels у меня такого точно не отдавал, спасибо завтра попробую.

Amir
18.04.2017
23:23:16
т.е. conses[][key] = 'key1' conses[][value] = 'value1' conses[][key] = 'key2' conses[][value] = 'value2' без значение в скобках стоит неоднозначность а так conses[0][key] = 'key1' conses[0][value] = 'value1' conses[1][key] = 'key2' conses[1][value] = 'value2' ясно что к чему
понятно а как сделать без указания иднексов, дело в том что кол-о элементов не известно и писать N-e количество "conses[<N>][value]": required: true remote: url: validate_url type: 'get' как то не то

Shamil
18.04.2017
23:35:19
As you may have heard, we have recently launched encrypted voice calls for Telegram. They are super-easy to use and improve themselves over time using machine learning. Personally, I rarely make voice calls. When I lived in Russia, I developed the habit of NEVER speaking over the phone, as every conversation was being recorded by corrupt law enforcement agencies. This habit stayed with me even after I left Russia a few years ago. I don't expect agencies in other countries to have more respect for privacy than their Russian counterparts. In my opinion, they're the same everywhere, some are just better at marketing. My phone habits may change now that I use secure calls via Telegram to communicate with my team and family members. Unfortunately, not everyone in the world will be able to enjoy the same. In countries like Saudi Arabia, Telegram traffic is throttled in order to discourage usage. In others, like China and Oman, it's blocked completely. In Iran, where Telegram has some 40 million active users, Telegram voice calls have been completely blocked by the country's internet providers and mobile operators following an order from the judiciary (more about this here – http://telegra.ph/Telegram-Calls-in-Iran-NEWS). Telegram has historically had problems with regulators in some parts of the world because, unlike other services, we consistently defended our users' privacy and have never made any deals with governments. In three and a half years of existence to date, Telegram disclosed exactly zero bytes of users' data to any third-party. Services like WhatsApp, on the other hand, are not blocked in China, Saudi Arabia, Iran, or other countries with a history of censorship. This is the case because WhatsApp (and its parent company Facebook) are eager to trade user trust for an increased market share. The claim that “WhatsApp and third parties can’t read or listen to your WhatsApp messages and calls” – is completely false. WhatsApp actually can read and listen in to your calls and messages, as they are able to invisibly change the encryption keys for 99.99% of their users (more about this backdoor-disguised-as-a-feature here – http://telegra.ph/whatsapp-backdoor-01-16). So much for "End-to-End Encryption". Moreover, third parties like Google or Apple have direct access to most of WhatsApp's users' chat history. This is because WhatsApp tricked the majority of users into allowing third party backups. And the sharing doesn't stop with just these third parties. Apple and Google in turn have to deal with data requests from all the countries they have business in, and so the data flows. By claiming that they are secure, our competitors may be involved in the single largest case of consumer fraud in human history. By comparison, Telegram relies on end-to-end encryption assisted by a built-in encrypted and distributed cloud for messages and media. The relevant decryption keys are split into parts and are spread across different jurisdictions. This structure makes your cloud data a hundred times more protected and secure than when it is stored by Google, Facebook, or Apple. No wonder governments and regulators are unhappy with Telegram. Well, let them block us as much as they want. We won't change our principles or betray our users. I know it’s not great to have Telegram (or parts of it) restricted in your country. But sometimes it’s better to stop using a communication service entirely than to keep using it with misplaced trust in its security. It's why I avoided voice calls for years, in Russia and beyond. It's also why I'm coming back to them now, on Telegram.

Верите?)

Amir
19.04.2017
03:18:25
Ребята Как например запустить код жава на определенной странице ready, он действует всему документу но мне надо чтобы только при наличии определенного блока на странице инициировался jquery validation

Vasiliy
19.04.2017
05:42:26
Amir
19.04.2017
06:58:56
вобщем мне надоела писать свой фрейворк UI элементов использую для сетки Susy подскажите подходящий только UI framework

Dima
19.04.2017
07:54:54
Materialize

Если не с джиквери, а с вью

То elementui

Nursultan
19.04.2017
08:03:31
кто нибудь работал с API vimeo?

Google
Nursultan
19.04.2017
08:03:46
надо загрузить видео с вимео на сайт

Vasiliy
19.04.2017
08:52:33
UI - https://purecss.io/

trickster
19.04.2017
11:22:58
привет всем, вопрос по интеркому, интегрировал ли кто-нибудь, были ли проблемы с ивентами из интеркома при ajax-ах

Eugene
19.04.2017
15:00:35
Ребят подскажите. https://gist.github.com/Evshved/c834dc5284786c2635f6d5b50a355bed есть такая проблема, @details={:image=>[{:error=>:blank}]}, @messages={:image=>["can't be blank"]}>

Admin
ERROR: S client not available

Vasiliy
19.04.2017
15:03:12
у тя файл должен быть в image

Rack::Test::UploadedFile.new(file) так попробуй указать image только вместо file путь к файлу

как-то типа так Rails.root.join('spec', 'support', 'images', 'test.png')

v
19.04.2017
15:05:18
он же путь к файлу туда сохраняет

Vasiliy
19.04.2017
15:05:46
сохраняет да, а работает с файлом

Eugene
19.04.2017
15:06:20
сохранил когда закоммитил Uploader

Vasiliy
19.04.2017
15:06:52
он под капотом эти махинации делает, ему надо давать файл, а он уже сам путь сохраняет, если даёшь строку - то не работает

v
19.04.2017
15:07:43
PinImage.new(pin_id: 2744, image: "123123123") - а чего эта строчка должна достичь?

вот это 123123

Vasiliy
19.04.2017
15:08:02
видимо создать объект PinImage ?

Eugene
19.04.2017
15:08:20
Мне нужно пока для Update

v
19.04.2017
15:08:23
мне 123 не понятен

Vasiliy
19.04.2017
15:08:26
а 123123123 - это видимо имя файла, _тестового_

Google
Vasiliy
19.04.2017
15:08:59
я с тестами наебся в общем, и только через Rack::Test::UploadedFile.new(file) ок работало, в принципе ничего сложного

Eugene
19.04.2017
15:09:07
ему пофиг что удалять в строке путь или дефолтную строку

Vasiliy
19.04.2017
15:10:09
можно для упрощения тестов сделать так module SharedFunctions def uploaded_file(file = Rails.root.join('spec', 'support', 'images', 'test.png')) Rack::Test::UploadedFile.new(file) end end RSpec.configure do |config| config.include SharedFunctions end и делать image: uploaded_file

Anton
19.04.2017
17:58:38
как лучше интегрировать виджет фейсбук/вк/инстаграм, с помощью айфрейм виджета или гем есть какой-то?

просто показывать группу и кнопочка на подписку

focusshifter
19.04.2017
17:59:52
А какую работу должен выполнить гем будет?

Anton
19.04.2017
18:01:40
может видел, на сайтах превью группы: участники, кол-во и т.п., и кнопка подписки

v
19.04.2017
18:02:20
который на страницу вставить

берешь и вставляешь во вьюшку

focusshifter
19.04.2017
18:03:02
может видел, на сайтах превью группы: участники, кол-во и т.п., и кнопка подписки
Нет, какую работу гем должен выполнить, кроме как 3 строки вставить

Andiskiy
19.04.2017
20:51:55
как лучше интегрировать виджет фейсбук/вк/инстаграм, с помощью айфрейм виджета или гем есть какой-то?
Зачем тебе гем? В документации к апи ВК можно создать этот виджет, всего три строчки вставляешь туда где тебе нужно.

Roman
19.04.2017
21:09:41
Ребят, всем привет. Кто нибудь юзал rails_admin с русской локализацией? Для модели User он использует other и как следствие "Список пользователи". Если поменять на "пользователей", то и в левом меню оно будет. Не красиво. Есть решение?

Amir
20.04.2017
03:56:16
вот к***з почему рельц вытаскивает из цикла скрытые input поля и размещает отдельно

Страница 980 из 1684