Joomla 4. Компонент K2 и форк K2ForJ4 (18 янв 2024)

Если вас, как и меня, достало выслушивать (вычитывать) бесконечные обещания разработчика K2 опубликовать версию компонента K2 под Joomla 4 (без чего невозможно реализовать апгрейд from Joomla 3 to Joomla 4) - воспользуйтесь форком K2ForJ4. Который в данный момент установлен и без каких-либо проблем работает на этом веб-сайте.

ActiveModel. Use validations in model without any DB relations

Больше
6 года 1 мес. назад #1 от serge
В качестве источников и/или сопутствующих материалов укажу отличную статью Non-ActiveRecord models in Rails 4 (все без изменений для Rails 5) и обсуждение Rails validation from controller на StackOverflow.

Таким образом, за более подробным изложением - велкам по ссылкам, здесь же только код живого примера реализации Rails validation на основе ActiveModel для данных, которые не записываются в базу данных приложения.

Итак, модель:

feedback.rb
Code:
class Feedback include ActiveModel::Model attr_accessor :name, :email, :address, :message, :suggestion # fields validation for the database. validates :name, presence: true validates :email, presence: true, length: {in:9..255} validates :address, presence: true validates :message, presence: true validates :suggestion, presence: true end



feedbacks_controller.rb
Code:
class FeedbacksController < ApplicationController def new @feedback = Feedback.new end def create @feedback = Feedback.new(feedback_params) respond_to do |format| if @feedback.valid? format.html { redirect_to success_path, notice: 'Feedback was successfully submited.' } else format.html { render :new } end end end def success end private def feedback_params params.require(:feedback).permit(:name, :email, :address, :message, :suggestion) end end


и вьюха:

new.html.erb
Code:
<h1>New Feedback</h1> <%= form_for(@feedback) do |f| %> <% if @feedback.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@feedback.errors.count, "error") %> prohibited this feedback from being saved:</h2> <ul> <% @feedback.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :email %><br> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :address %><br> <%= f.text_field :address %> </div> <div class="field"> <%= f.label :message %><br> <%= f.text_area :message %> </div> <div class="field"> <%= f.label :suggestion %><br> <%= f.text_area :suggestion %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> <%= link_to 'Back', feedbacks_path %>

Для реализации приложения оптимально для начала воспользоваться генераторами Rails, создав контроллер и модель:
Code:
# Create a Controller with only new, create & success Actions rails generate controller feedbacks new create success --skip-routes # Create a Model rails generate model feedback name:string email:string address:string message:text suggestion:text

, также сконфигурировать роутер:
Code:
resources :feedbacks, :only => [:new, :create] get 'feedbacks/success' => 'feedbacks#success', as: :success

Ну а остальное сами. :)
Для тестирования в консоли (воочию убедиться, что запись в db не производится):

Open up your Terminal, go to your project directory, and type the commands below.

Code:
rails db # to start the database client in your console. SQLite> .tables # to list all the tables in your database (DB is selected by default). SQLite> .headers on # to display the Column Names in your results. SQLite> select * from feedbacks; # to see all the feedback in the database.


А я смогу! - А поглядим! - А я упрямый!

Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.

Dev banner 1
Больше
6 года 3 нед. назад #2 от Aleksej

serge пишет: В качестве источников и/или сопутствующих материалов укажу отличную статью...


и я поступлю так же:
rusrails.ru/active-model-basics

Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.

Больше
6 года 3 нед. назад #3 от Aleksej
К одноименной статье блога.

Вариант с использованием rescue вместо elsif:
Code:
def weather @weather = Form.new(form_params) @lookup = Weather.call([params[:request]].join(",")) (flash[:notice] ||= []) << 'Success. ID: ' + params[:request] + '. Server response: ' + response.status.to_s rescue Weather::NoFoundError (flash[:error] ||= []) << 'Error. Invalid ID: ' + params[:request] + '. Data not received. Server response: ' + response.status.to_s render ... rescue Weather::UnvalidError # some crap end
Code:
params.permit(:request) # => params.require(:request).permit(:request)

Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.

Работает на Kunena форум