Trix - undefined method `to_key' - ruby-on-rails

I have a CategoryForm obejct for which I render a form and I installed Trix editor (gem 'trix') to let my users format the text. After installing Trix I am getting undefined method 'to_key'. Here's my current setup.
app/assets/javascripts/admins/categories/categories.js
//= require trix
app/assets/stylesheets/admins/categories/categories.css
*= require trix
CategoryForm
class CategoryForm
attr_accessor :short_desc_pl, :short_desc_en, :short_desc_de,
:long_desc_pl, :long_desc_en, :long_desc_de,
:resource
def initialize(params = {})
#resource = Category.find(params[:id])
generate_fields
end
private
def generate_fields
#short_desc_pl = #resource.short_description['pl']
#short_desc_en = #resource.short_description['en']
#short_desc_de = #resource.short_description['de']
#long_desc_pl = #resource.long_description['pl']
#long_desc_en = #resource.long_description['en']
#long_desc_de = #resource.long_description['de']
end
end
Form
<%= form_for category_form, as: 'category', url: admins_category_path(category_form.resource), method: :patch do |form| %>
<table class="table">
<col>
<colgroup span="2"></colgroup>
<colgroup span="2"></colgroup>
<tr>
<td rowspan="2"></td>
</tr>
<tr>
<th scope="col">PL</th>
<th scope="col">EN</th>
<th scope="col">DE</th>
</tr>
<tr>
<th scope="row">Krótki opis</th>
<td><%= form.text_field :short_desc_pl, class: 'form-control' %></td>
<td><%= form.text_field :short_desc_en, class: 'form-control', required: true %></td>
<td><%= form.text_field :short_desc_de, class: 'form-control', required: true %></td>
</tr>
<tr>
<th scope="row">Długi opis</th>
<td><%= form.trix_editor :long_desc_pl, size: "20x20", class: 'form-control', required: true %></td>
<td><%= form.text_area :long_desc_en, size: "20x20", class: 'form-control', required: true %></td>
<td><%= form.text_area :long_desc_de, size: "20x20", class: 'form-control', required: true %></td>
</tr>
</table>
<div class="actions">
<%= form.submit 'Zapisz' %>
</div>
<% end %>
What am I doing wrong?
UPDATE
I even changed my form to use #category
<%= form_for category, as: 'category', url: admins_category_path(category), method: :patch do |form| %>
...
and I am not getting any error but the editor simply does not render. I am using Webpacker, Rails 5.1.

Related

how to get multiple records from static form in rails for database

The main form
<%= p.fields_for :prd_province_vise_deliveries do |j| %>
<%= render(:partial => 'prd_province_vise_delivery_field', :locals => {:k => j})%>
<% end %>
and this is my prd_province_vise_delivery_field partial
<div>
<table class="table-striped">
<thead>
<tr>
<th> Province name </th>
<th> Delivery rate (Rs)</th>
<th> Delivery period(Days) </th>
</tr>
</thead>
<tbody>
<tr>
<td><%= k.label :province_name , 'Western'%></td>
<td><%= k.text_field(:delivery_rate, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%> </td>
<td> <%= k.text_field(:delivery_period, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%></td>
</tr>
<tr>
<td><%= k.label :province_name , 'Southern'%> </td>
<td><%= k.text_field(:delivery_rate, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%> </td>
<td> <%= k.text_field(:delivery_period, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%></td>
</tr>
<tr>
<td><%= k.label :province_name , 'Nothern'%> </td>
<td><%= k.text_field(:delivery_rate, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%> </td>
<td> <%= k.text_field(:delivery_period, {placeholder: '0', class: 'form-control input_border input_field_text_align_right'})%></td>
</tr>
</tbody>
</table>
</div>
but with this approach i could not get the params for the request
can anyone suggest a method
If you are using CoffeeScript to send the data from the FORM
create the array first, and loop through the text boxes and collect data
arr = []
$('input#day_id').each ->
arr.push $(this).val()
convert the array
sample_array = JSON.stringify(arr)
Call the ajax
$.ajax '/controller',
type: "POST",
data: { schedule: { days: sample_array }},
async: true
success:(data) ->
If you are submitting the form
create the form as follows
<% #class_variable.each do |f| %>
<%= text_field_tag 'delivery_rate[]', delivery_rate %>
<%= text_field_tag 'delivery_amount[]', delivery_amount %>
<% end %>

Search form don't update table in RoR

I'm trying to write a filter for the table. Here is the code:
.../models/message.rb
Class Message < ActiveRecord::Base
include Filterable
belongs_to :user
default_scope -> { order('created_at DESC') }
validates :user_id, presence: true
validates :content, presence: { message: "Выберите файл послания для загрузки!" }, file_size: { less_than_or_equal_to: 20.megabytes }
validates :fromdate, presence: true
validates :tilldate, presence: true
mount_uploader :content, ContentUploader
scope :id, -> (id) {where id: id }
scope :tariff, -> (tariff) { where tariff: tariff }
scope :status, -> (status) { where("status like ?", "#{status}%")}
end
.../controllers/concerns/filterable.rb
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
.../controllers/messages_controller.rb
...
def index
#messages = Message.filter(params.slice(:id, :tariff, :status)).paginate(page: params[:page], :per_page => 10)
end
...
.../views/messages/index.html.erb
...
<table class="table table-bordered">
<thead>
<tr>
<th>Клиент</th>
<th>№</th>
<th>Дата</th>
<th>Послание</th>
<th>Тариф</th>
<th>Показ с</th>
<th>до</th>
<th>Стоимость, р.</th>
<th>Статус</th>
<% if current_user.admin? %>
<th>Модератор</th>
<% end %>
</tr>
</thead>
<tbody>
<tr>
<%= form_tag messages_path, method: "get" do %>
<td><%= text_field_tag "client" %></td>
<td><%= text_field_tag "id", nil, size: 1 %></td>
<td></td>
<td><%= submit_tag "Выбрать" %><br><br><%= button_tag "Очистить" %></td>
<td><%= select_tag "tariff", options_for_select(["", "1. Вечер", "2. Весь день", "1001. ВЕЧЕР БЕСПЛАТНО", "1002. ДЕНЬ БЕСПЛАТНО"]), {} %></td>
<td></td>
<td></td>
<td></td>
<td><%= select_tag "status", options_for_select(["", "В обработке", "Исполняется", "Отклонена", "Выполнена"]), {} %></td>
<td></td>
<% end %>
</tr>
<%= render #messages %>
</tbody>
</table>
</div>
...
.../views/messages/_message.html.erb
...
<% case message.status
when "В обработке"
#messagecolor="warning"
when "Исполняется"
#messagecolor="success"
when "Выполнена"
#messagecolor="info"
when /Отклонена.*/
#messagecolor="danger"
end
unless message.moderator.nil?
#moderator = User.find(message.moderator).name
end
%>
<tr class=<%= #messagecolor %> data-message_id="<%= message.id %>">
<% if current_user.admin? || current_user.role == "Модератор" %>
<td><%= message.user.name %></td>
<% end %>
<td><%= message.id %></td>
<td><%= message.created_at.strftime("%d/%m/%Y %T %z") %></td>
<td><img src="<%= message.content_url(:thumb) %>" data-toggle="modal" data-target="#myModal" data-content="<%= message.content_url%>"></td>
<td><%= message.tariff %></td>
<td><%= message.fromdate.strftime("%d/%m/%Y") %></td>
<td><%= message.tilldate.strftime("%d/%m/%Y") %></td>
<td><%= message.cost %></td>
<td class="status">
<%= message.status %>
<% if (current_user.admin? || current_user.role == "Модератор") && message.status == "В обработке" %>
<br>
<div class="btn-group">
<button type="button" class="btn btn-success" data-status="Исполняется" data-message_id="<%= message.id %>">Принять</button>
<button type="button" class="btn btn-danger" data-status="Отклонена" data-message_id="<%= message.id %>">Отклонить</button>
</div>
<% end %>
<% if (current_user.admin? || current_user.role == "Модератор") && message.status == "Исполняется" %>
<br>
<%= link_to "Изменить", edit_message_path(message.id), :class => "btn btn-info" %>
<% end %>
</td>
<% if current_user.admin? %>
<td class="moderator">
<%= #moderator %><br>
<%= message.updated_at.strftime("%d/%m/%Y %T %z")%>
</td>
<% end %>
</tr>
...
The filter only works after the page is refreshed. It is worth to get back to the page through the menu - the form button does not work, update by F5 - it works. Why?
I will also be grateful if you tell me how to save the selected filter values ​​in the fields after it is applied.
I found the answer to my main question: it need to include the entire table into the form in .../views/messages/index.html.erb
...
<%= form_tag messages_path, method: "get" do %>
<table class="table table-bordered">
<thead>
<tr>
<th>Клиент</th>
<th>№</th>
<th>Дата</th>
<th>Послание</th>
<th>Тариф</th>
<th>Показ с</th>
<th>до</th>
<th>Стоимость, р.</th>
<th>Статус</th>
<% if current_user.admin? %>
<th>Модератор</th>
<% end %>
</tr>
</thead>
<tbody>
<tr>
<td><%= text_field_tag "client" %></td>
<td><%= text_field_tag "id", nil, size: 1 %></td>
<td></td>
<td><%= submit_tag "Выбрать" %><br><br><%= button_tag "Очистить" %></td>
<td><%= select_tag "tariff", options_for_select(["", "1. Вечер", "2. Весь день", "1001. ВЕЧЕР БЕСПЛАТНО", "1002. ДЕНЬ БЕСПЛАТНО"]), {} %></td>
<td></td>
<td></td>
<td></td>
<td><%= select_tag "status", options_for_select(["", "В обработке", "Исполняется", "Отклонена", "Выполнена"]), {} %></td>
<td></td>
</tr>
<%= render #messages %>
</tbody>
</table>
<% end %>
</div>
...
And now it works correctly.

Form_tag do not add check_box_tag value into parameters

I have Pieces model, which is store item's parts. When I need, I'm asking to users, check pieces is ok or nok with generated forms.
I am creating reports model to store the forms which I asked from users.
So, when I generate the forms check_box and and text_field works fine. But when I submit the form, I can't get check_box values as a parameter.
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"5OmdXCDixwxru2yBtB3YmT3YF/ZqOByoAJ3J29TyJikxJdA+RXAvGjwu8MBIPlJCROFx4V7AUcA7IIqIgthD9g==",
"notes"=>{"79"=>"asdasda","84"=>""},
"commit"=>"Submit",
"id"=>"5"}
here is my edit.html.erb
<%- model_class = Report -%>
<div class="page-header">
<h1><%=t '.title', :default => [:'helpers.titles.edit', 'Edit %{model}'], :model => model_class.model_name.human.titleize %></h1>
</div>
<% if #report.errors.any? %>
<div id="error_expl" class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><%= pluralize(#report.errors.count, "error") %> prohibited this report from being saved:</h3>
</div>
<div class="panel-body">
<ul>
<% #report.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<table class="table table-striped">
<thead>
<tr>
<th><%= model_class.human_attribute_name(:status) %></th>
<th><%= model_class.human_attribute_name(:serial_no) %></th>
<th><%= model_class.human_attribute_name(:category) %></th>
<th><%= model_class.human_attribute_name(:name) %></th>
<th><%= model_class.human_attribute_name(:brand) %></th>
<th><%= model_class.human_attribute_name(:model) %></th>
<th><%= model_class.human_attribute_name(:quantity) %></th>
</tr>
</thead>
<tbody>
<%= form_tag(report_path(#report), :method => :patch) do %>
<% #pieces.each do |piece| %>
<tr>
<td><div class="form-group">
<%= check_box_tag(:status, name: "status["+piece.id.to_s+"]", class: 'form-control') %>
</div></td>
<td><%= piece.try(:serial_no) %></td>
<td><%= piece.item.category.name %></td>
<td><%= piece.item.name %></td>
<td><%= piece.item.brand %></td>
<td><%= piece.item.model %></td>
<% if piece.serial_no.start_with?("D") %>
<td><%= piece.item.pieces.count %> <%= piece.item.unit.name %></td>
<% else %>
<td><%= piece.item.pieces.sum(:quantity) %> <%= piece.item.unit.name %></td>
<% end %>
</tr>
<tr>
<td colspan=7 class="hidden" id="hebele">
<%= text_field_tag(:note,"", placeholder: "Note ", name: "notes["+piece.id.to_s+"]",class: "form-control ") %>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<%= submit_tag("Submit",:class => 'btn btn-primary') %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")), reports_path, :class => 'btn btn-default' %>
</div>
</div>
<% end %>
<script type="text/javascript">
$("[id='status']").bootstrapSwitch({
size: 'mini',
onColor: 'success',
offColor: 'danger',
indeterminate: true,
onSwitchChange: function(event, state) {
if (state == false){
$("#hebele").removeClass('hidden');
}else if(state == true){
$("#hebele").addClass('hidden');
}
}
});
</script>
controller:
def edit
#pieces = #report.pieces.joins(:item).group(:item_id)
#report = Report.find(params[:id])
end
You need to define the value of the check_box_tag:
<%= check_box_tag :status, piece.id, class: 'form-control' %>
If you're editing a #report, you'll be best using form_for:
<table>
<tbody>
<%= form_for #report do |f| %>
<% #pieces.each do |piece| %>
<tr>
<td>
<div class="form-group">
<%= f.check_box :status, class: 'form-control', price.id %>
</div>
</td>
<td><%= piece.try(:serial_no) %></td>
<td><%= piece.item.category.name %></td>
<td><%= piece.item.name %></td>
<td><%= piece.item.brand %></td>
<td><%= piece.item.model %></td>
<% if piece.serial_no.start_with?("D") %>
<td><%= piece.item.pieces.count %> <%= piece.item.unit.name %></td>
<% else %>
<td><%= piece.item.pieces.sum(:quantity) %> <%= piece.item.unit.name %></td>
<% end %>
</tr>
<tr>
<td colspan=7 class="hidden" id="hebele">
<%= f.text_field :note, placeholder: "Note", class: "form-control" %>
</td>
</tr>
<% end %>
<tr><td colspan="7"><%= f.submit, class: "btn btn-primary" %></td></tr>
<% end %>
</tbody>
</table>

How to change values which get from check box into SQL condition?

I use check_box_tag to get selected beacon, and i to use collection_select to define a value. when user press the button, I want to all selected beacons change value into what collection_select choose, but I don't know how to use ids[] to set my condition like "where...in ..."
here is my action, I want params[:ids] change in to just like [1,2,3]
#beacons = Beacon.where(:id => params[:ids]).update_all(:installer_id => params[:account][:installer_id])
here is my table:
<table class="col-md-12 table-bordered table-striped table-condensed cf">
<thead class="cf">
<th>Check</th>
<th>BeaconUUID</th>
<th>BeaconCategory</th>
<th>BeaconLocate</th>
<th>BeaconName</th>
<th>BeaconAddress</th>
<th>Assign</th>
</thead>
<tbody>
<% #beacons.each do |beacon| %>
<tr>
<td><%= check_box_tag "ids[]", beacon.id %></td>
<td><%= beacon.beacon_uuid %></td>
<td><%= beacon.cid %></td>
<td><%= beacon.lid %></td>
<td><%= beacon.beacon_name %></td>
<td><%= beacon.beacon_address %></td>
<% if beacon.installer_id.nil? %>
<td>not assign</td>
<% else %>
<td>assigned:<%= beacon.installer_id %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<%= form_tag assigned_beacons_path, :method => 'post' do %>
<td><%= collection_select(:account, :installer_id, Account.where('manager_id = ?',session[:user_id]), :id, :email, {:prompt => 'choose!'}, :style => "width: 100px;") %></td>
<td><p data-placement="top" data-toggle="tooltip" title="Edit"><%= submit_tag 'assign', class: "btn btn-info btn-xs"%></p></td>
<% end %>
As was pointed out in comments, check_box_tag should be moved inside of form_tag block:
<%= form_tag assigned_beacons_path, :method => 'post' do %>
<table class="col-md-12 table-bordered table-striped table-condensed cf">
<thead class="cf">
<th>Check</th>
<th>BeaconUUID</th>
<th>BeaconCategory</th>
<th>BeaconLocate</th>
<th>BeaconName</th>
<th>BeaconAddress</th>
<th>Assign</th>
</thead>
<tbody>
<% #beacons.each do |beacon| %>
<tr>
<td><%= check_box_tag "ids[]", beacon.id %></td>
<td><%= beacon.beacon_uuid %></td>
<td><%= beacon.cid %></td>
<td><%= beacon.lid %></td>
<td><%= beacon.beacon_name %></td>
<td><%= beacon.beacon_address %></td>
<% if beacon.installer_id.nil? %>
<td>not assign</td>
<% else %>
<td>assigned:<%= beacon.installer_id %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<td><%= collection_select(:account, :installer_id, Account.where('manager_id = ?',session[:user_id]), :id, :email, {:prompt => 'choose!'}, :style => "width: 100px;") %></td>
<td><p data-placement="top" data-toggle="tooltip" title="Edit"><%= submit_tag 'assign', class: "btn btn-info btn-xs"%></p></td>
<% end %>
Also, dangling <td> blocks don't look good, you should move them into this or another <table> as well.

Rails nested_form gem updates wrong parent data

I have the following in one of my forms. With this code I can dynamically add divisions, sub_divisions and sub_sub_divisions on the page. The problem is the sub_sub_divisions I add are saved to the first sub_division even though they are correctly displayed on other sub_divisions on the view. I don't know what is happening between the view and what is passed to controller to make this error. Thanks a lot.
<%= nested_form_for #division do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<table>
<tr>
<td>
<%= f.label t("name") %>
<%= f.text_field :name, class: 'form-control' %>
</td>
<td>
<%= f.label t("description") %>
<%= f.text_field :description, class: 'form-control' %>
</td>
</tr>
<tr><td><h3><%=t :sub_divisions %></h3></td></tr>
<tr>
<td colspan=4>
<table id="sub_divs" class="table table-condensed table-striped">
<tr><th><%=t :name %></th><th><%=t :description %></th></tr>
<%= f.fields_for :sub_divs, :wrapper => false do |sub_div| %>
<tr class="fields">
<td><%= sub_div.text_field :name, class: 'form-control' %></td>
<td><%= sub_div.text_field :description, class: 'form-control' %></td>
<td><%= sub_div.link_to_remove t("delete") %></td>
</tr>
<td colspan=3>
<table id="<%= 'sub_sub_divs' + sub_div.index.to_s %>">
<tr><th><%=t :name %></th><th><%=t :description %></th></tr>
<%= sub_div.fields_for :sub_sub_divs,
:wrapper => false do |sub_sub_div| %>
<tr class="fields">
<td><%= sub_sub_div.text_field :name,
class: 'form-control' %></td>
<td><%= sub_sub_div.text_field :description, class:
'form-control' %></td>
<td><%= sub_sub_div.link_to_remove t("delete") %></td>
<td><%= sub_sub_div.hidden_field :id,
value: sub_sub_div.object.sub_div_id %></td>
</tr>
<% end %>
</table>
</td>
</tr>
<tr>
<td colspan=3 class="pull-right">
<%= sub_div.link_to_add t("add") +
t("sub") + t('sub') + t('div'), :sub_sub_divs,
:data => { :target => "#"+"sub_sub_divs" +
#{sub_div.index.to_s}", id: sub_div.object.id} %>
</td>
</tr>
<% end %>
</table>
</td>
</tr>
<tr><td colspan=2 class="pull-right">
<%= f.link_to_add t("add") + t("sub") + t('div'),
:sub_divs, :data => { :target => "#sub_divs"} %></td></tr>
<tr><td><%= f.submit t("update"), class: "btn btn-primary" %></td></tr>
</table>
<% end %>
Outside of your call to
<%= f.fields_for :sub_divs, :wrapper => false do |sub_div| %>
You should iterate over the sub_divs:
<%= #division.sub_divs.each do |sub_div| %>
And then pass each one to the fields_for call as the 2nd parameter:
<%= f.fields_for :sub_divs, sub_div, :wrapper => false do |sub_div| %>
Do the same for the next nested sub_sub_div and finally:
<%= sub_sub_div.hidden_field :id,
value: sub_sub_div.object.sub_div_id %>
...will have the correct sub_div_id

Resources