Working with Rails arrays in Postgres - ruby-on-rails

I have a postgres column called content which is an array.
But when trying to use it in a form I'm getting:
can't cast ActionController::Parameters to text
Despite the fact that the output looks pretty good:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"NkK4BggxknfEn0A8shTs06xmesERaZdYtZdl9oEEUTk=",
"notification_template"=>{"content"=>{"0"=>"Join us {{event_time}} {{{twitter_name}}} to win Big! hint: {{{question}}} #quiz {{location_tags}} {{url}} sdfsdfsdf"}},
"commit"=>"Update Notification template",
"id"=>"25"}
strong params
params.require(:notification_template).permit(:name, :content => {})
routes
resources :notification_templates do
get 'edit/:id', to: 'notification_templates#edit_content', as: 'edit_content'
end
controller
def edit_content
#notification_template = NotificationTemplate.find(params[:notification_template_id])
end
def update
if #notification_template.update(notification_template_params)
redirect_to admin_notification_template_path(#notification_template), notice: 'Social message was successfully updated.'
else
render action: 'edit'
end
end
my form
the url looks like: /notification_templates/25/edit_content/7 # custom action, but uses normal update
<%= simple_form_for([:admin, #notification_template]) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.simple_fields_for :content do |fields| %>
<%= fields.input params[:id], input_html: { value: #notification_template.content[params[:id].to_i] } %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
the DB column
add_column :notification_templates, :content, :text, array: true, default: []
Lastly, I was unsure about the conventions for adding it. The above worked fine, but I also noticed other possibilities such as
add_column :notification_templates, :content, :text, array: true, default: []
add_column :notification_templates, :content, :sting, array: true, default: []
add_column :notification_templates, :content, :text, array: true, default: {}
I choose the first one on the basis that a string wouldn't allow for as many characters as I might eventually need and text is more convenient. Also the default of [] vs {} or '{}'
But in postgres is see content text[] DEFAULT '{}'::text[]
log
Started PATCH "/admin/notification_templates/25" for 127.0.0.1 at 2014-11-28 14:25:43 +0100
Processing by Admin::NotificationTemplatesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NkK4BggxknfEn0A8shTs06xmesERaZdYtZdl9oEEUTk=", "notification_template"=>{"content"=>{"4"=>"{{{question}}} Study up and stop by {{{twitter_name}}} {{event_time}} for a #quiz {{location_tags}} {{url}} sdfsdfsdf"}}, "commit"=>"Update Notification template", "id"=>"25"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
NotificationTemplate Load (0.5ms) SELECT "notification_templates".* FROM "notification_templates" WHERE "notification_templates"."id" = $1 LIMIT 1 [["id", 25]]
(0.3ms) BEGIN
(0.3ms) ROLLBACK
Completed 500 Internal Server Error in 54ms
Reporting exception: can't cast ActionController::Parameters to text
TypeError (can't cast ActionController::Parameters to text):
app/controllers/admin/notification_templates_controller.rb:40:in `update'
Rendered /Users/holden/.rvm/gems/ruby-2.0.0-p481#questionone-2.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.1ms)
Rendered /Users/holden/.rvm/gems/ruby-2.0.0-p481#questionone-2.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
Rendered /Users/holden/.rvm/gems/ruby-2.0.0-p481#questionone-2.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.4ms)
Rendered /Users/holden/.rvm/gems/ruby-2.0.0-p481#questionone-2.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (27.5ms)
UPDATE
I also observed that update array type field doesn't work as expected in the console.
eg. if I attempt to update a member of the array, something = record.content[2] = 'blah' it appears to work. But when I save the record it doesn't update it.

Yeah, Rails postgres Arrays are still a bit wonky. Hstore is a bit easier.
You may be better served going thru a virtual attribute and doing what you want expressly rather than relying on standard rails behavior through a form.
eg.
def content_member=(member)
unless member.blank?
self.content_will_change!
self.content[member.keys.first.to_i] = member.values.first
end
end
You also need to let rails know if you're going to update a member of an array, that's why it doesn't work in the console.
There's a full explanation here:
Rails 4 Postgresql array data-type: updating values

Related

Image from polymorphic model does't display

I have a model named Hen:
class Hen < ApplicationRecord
has_many :pictures, as: :imageable
validates :name, :description, presence: true
end
I added the :picture to whitelisted params in the HensController as well
Picture model:
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
has_attached_file :image
end
When creating new Hen, I can check that the instance is created.
In console Hen.last.pictures returns
[["imageable_id", 3], ["imageable_type", "Hen"], ["LIMIT", 11]]
=> #
,so I assume that it is fine there.
... but I do not know how to dispay it in the view section. After some tries I have done that:
<p><%= #hen.pictures do |pic| %></p>
<%= image_tag pic.url %>
<% end %>
It dispays
#<Picture::ActiveRecord_Associations_CollectionProxy:0x00005640044034f0>*
because I left the "=" there (to check if there is any object inside), but the picture is not displayed. I checked some other variants like pic.image_url and nothing works for me. Other images on the page display without problems.
Console returns status 200:
Processing by HensController#show as HTML
Parameters: {"id"=>"3"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Hen Load (0.5ms) SELECT "hens".* FROM "hens" WHERE "hens"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/hens_controller.rb:16:in `show'
Rendering hens/show.html.erb within layouts/application
Rendered hens/show.html.erb within layouts/application (Duration: 5.9ms | Allocations: 3302)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 125ms (Views: 67.7ms | ActiveRecord: 10.7ms | Allocations: 36995)*
You're not actually looping through pictures. You need to use #hen.picutres.each or for picture in #hen.pictures. Without this, you're just passing a block to #hen.pictures; the block gets ignored and the expression returns #hen.pictures (Picture::ActiveRecord_Associations_CollectionProxy).
The equivalent plain-ruby would be
#hen.pictures { ... this block isn't used but it's not a syntax error ... }
instead of
#hen.pictures.each { |picture| ... this block is used by the `each` method }
Here <%= #hen.pictures do |pic|%> you are printing the picture url. you should not include = when you are looping <%= #hen %> wrong you should use <% #hen %> then you need to loop the pictures using each.
<% #hen.pictures.each do |pic| %>
<%= image_tag pic.url %>
<% end %>
if the picture url in hash try to convert it into string using .to_s
<%= image_tag pic.url.to_s %>
This may not be the direct answer for the problem, but I found that better option is to use ActiveStorage than creating Polymorphic associations between models.
First, install the ActiveStorage:
rails active_storage:install
then add macro has_one_attached or has_many_attached to the models:
class Hen < ApplicationRecord
has_one_attached :image
validates :name, :description, presence: true
end
add to the view form:
<%= f.file_field :image %>
whitelist the :image attribute:
def hens_params
params.require(:hen).permit(:name, :description, :image)
end
Done.
To dispay the image in views:
<%= image_tag hen.image if hen.image.attached? %>
No need to create new model or to nest attributes.

Limit scope on rails-jquery-autocomplete (rails3-jquery-autocomplete) gem - where clause issue

There is a recommended solution and it seems to work. The issue is in my where clause and I'm not sure what's wrong.
For reference, here is the solution(s):
https://stackoverflow.com/a/7250426/4379077
https://stackoverflow.com/a/7250341/4379077
I am trying to scope users that are members of the current_user's family tree memberships(branches) user's within my Nodes controller. This would normally be done using this code (current_user.family_tree.memberships).
Note I have successfully set this up to autocomplete showing all users (User.all):
In my routes:
resources :nodes do
get :autocomplete_user_first_name, :on => :collection
end
In my Node controller I have the following code:
autocomplete :user, :first_name, :extra_data => [:last_name, :email],
display_value: :full_name
And in my view I have the following form:
<%= form_for node do |f| %>
<%= f.label :user_tags %>
<%= f.autocomplete_field :user_tags, autocomplete_user_first_name_nodes_path, 'data-auto-focus' => true, value: nil %>
<%= f.submit %>
<% end %>
When I attempt to add the recommended solution to my nodes controller:
def get_autocomplete_items(parameters)
items = super(parameters)
items = items.where(:user_id => current_user.family_tree.memberships)
end
I get this message:
NoMethodError - super: no superclass method "get_autocomplete_items" for #<NodesController:0x007fc516692278>:
So, I found this article https://stackoverflow.com/a/18717327/4379077 and changed it to
def get_autocomplete_items(parameters)
items = active_record_get_autocomplete_items(parameters)
items = items.where(:user_id => current_user.family_tree.memberships)
end
It works, but I get the following error
PG::UndefinedColumn: ERROR: column users.user_id does not exist, so I changed the where clause to this :id => current_user.family_tree.memberships and I get this result
User Load (0.9ms) SELECT users.id, users.first_name, "users"."last_name",
"users"."email"
FROM "users" WHERE (LOWER(users.first_name) ILIKE 'mi%')
AND "users"."id" IN (SELECT "memberships"."id" FROM "memberships"
WHERE "memberships"."family_tree_id" = $1)
ORDER BY LOWER(users.first_name) ASC LIMIT 10 [["family_tree_id", 1]]
The issue is that I believe I need to get a collection within the membership model comparing the attribute membership.user_id to user.id. What am I doing wrong in my where clause?
Are Membership objects the same thing as Users?
if not, you need to get the user_id off the membership record
This line would need to change
# use pluck to get an array of user_ids.
items = items.where(:id => current_user.family_tree.memberships.pluck(:user_id))

Rails many-to-many creation fails

I have event and band models, which have a many-to-many relationship through event_bands. I am trying to change my create method to use chosen jQuery like in episode 258 of railscasts. I am not sure how to read the message from my localhost when I try to create an event:
Started POST "/events" for 127.0.0.1 at 2014-03-16 17:11:07 +0900
Processing by EventsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jx1Cm09uCwJcnY8573ZTRKMjH1BHWhlREFCfhij/AB0=", "event"=>{"name"=>"pojpj", "ko_name"=>"", "band_ids"=>["", "110"], "venue_id"=>"", "date(1i)"=>"2014", "date(2i)"=>"3", "date(3i)"=>"16", "time"=>"", "contact"=>"", "facebook"=>"", "ticket"=>"true", "price"=>"", "door_price"=>"", "ticket_url"=>"", "info"=>"", "info_ko"=>""}, "commit"=>"등록", "locale"=>"ko"}
Band Load (0.2ms) SELECT "bands".* FROM "bands" WHERE "bands"."id" = ? LIMIT 1 [["id", 110]]
(0.1ms) begin transaction
Band Exists (1.0ms) SELECT 1 AS one FROM "bands" WHERE ("bands"."name" = '...Whatever That Means' AND "bands"."id" != 110) LIMIT 1
(0.2ms) rollback transaction
Redirected to http://localhost:3000/events/new
It looks like it fails because the Band already exists in the database, but why is it doing that instead of creating the relation?
def new
#event = Event.new
end
def create
#event = Event.new(event_params)
if #event.save
flash[:notice] = "Event Created!"
redirect_to event_path(#event)
else
flash[:notice] = "Event not created!"
redirect_to new_event_path
end
end
private
def event_params
params.require(:event).permit(:name,
:ko_name,
:avatar,
:time,
:facebook,
:ticket,
:door_price,
:ticket_url,
:info_kr,
:contact,
:price,
:info,
:info_ko,
:venue_id,
:date,
band_ids: [])
end
Relevant part of the form:
<p>
<%= f.label "Bands" %><br />
<%= f.collection_select :band_ids, Band.order(:name), :id, :name, {}, {multiple: true} %>
</p>
I have accepts_nested_attributes_for :bands in the model and I think the relation is setup correctly because I can do a = Event.new(name: 'asdf', band_ids: [1,5]) a.save and it is persisted.
update: it seems the problem is coming from the empty item in band_ids. For some reason, rails is setting the param as band_ids: ['',3,5]. I can replicate the SQL message from my server by trying to create a new entry in the console like this: a = Event.create(name: 'asdfasdfasdfasdf2345', band_ids: ['', 3, 2]). But where is the empty first item coming from?
edit2: Disregard the above, it seems the problem is actually that there is no event_id to use in the association?
#messages={:"event_bands.event_id"=>["에 내용을 입력해 주세요"]}

Rails test for contents in a form

I have a Comment form that also contains an Attachment form.
Comment model contains:
accepts_nested_attributes_for :attachments
Comment form contains:
<%= f.fields_for :attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach %>
<% end %>
Comment Controller contains:
def new
#comment = Comment.new
#comment.attachments.build
If the user adds an Attachement, everything works fine.
I would like the user to be able to submit a Comment with or without an Attachment.
Right now, if the user enters a Comment without an attachment, the form re-displays and the Comment does not get created.
This is the log if I try to post a new Comment without an Attachement:
Started POST "/comments" for 127.0.0.1 at 2013-12-19 10:34:31 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"A6MOeMgoGUDmGiJr9PWinHVTAa7X63fgtA7+2my0A2Y=", "comment"=>{"user_id"=>"1", "status_date"=>"2013-12-19", "worequest_id"=>"10", "statuscode_id"=>"", "comments"=>"test", "attachments_attributes"=>{"0"=>{"name"=>""}}}, "_wysihtml5_mode"=>"1", "commit"=>"Save Comment"}
Tenant Load (0.3ms) SELECT "tenants".* FROM "tenants" WHERE "tenants"."subdomain" = 'ame' LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."tenant_id" = 1 AND "users"."id" = 1 LIMIT 1
(0.1ms) BEGIN
(0.1ms) ROLLBACK
I need to figure out the right code so that the Attachment fields show up in the form, but the Comment will get created if no Attachment is selected.
Maybe I need to put code in the Attachment controller?
You could use Rails present? method to check if the object is not blank:
#comment.attachments.build if #comment.attachments.present?
I changed the Comment model to this:
accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:attach].blank? }, :allow_destroy => true

Create a model attribute from checkbox input

This creates and saves a new row to my database. The problem is that I have a checkbox in my view file for a boolean value, but no matter whether the box is checked or not, the new row is always false. I also can't get any of the other attributes to show up as anything other than nil. Any ideas?
This is my view is:
<%= form_for(#setting) do |s| %>
<div class="field" >
<%= s.label :my_setting_attribute %>
<%= s.check_box(:my_setting_attribute) %>
</div>
<div class="actions">
<%= s.submit "Submit" %>
</div>
<% end %>
And my controller:
def new
#setting = Setting.new
end
def create
#setting = Setting.new(params[:setting])
if #setting.save
redirect_to :action => 'index', :id => #setting.id
else
redirect_to :action => 'error'
end
end
I think I have my route file set correctly:
resources :settings do
collection do
get :index
post 'settings/new'
get 'settings/show'
end
end
Here's the development log excerpt:
Started POST "/settings" for 10.7.94.191 at 2011-07-25 20:30:11 -0400
Processing by SettingsController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"xxxxxxxxxxx=", "setting"=>{"my_setting_attribute"=>"1", "other_setting_attribute"=>"hello"}, "commit"=>"Submit"}
ESC[1mESC[36mUser Load (0.1ms)ESC[0m ESC[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1ESC[0m
ESC[1mESC[35mSQL (0.1ms)ESC[0m BEGIN
ESC[1mESC[36mSQL (1.0ms)ESC[0m ESC[1mdescribe `settings`ESC[0m
ESC[1mESC[35mAREL (0.3ms)ESC[0m INSERT INTO `settings` (`facebook_token`, `twitter`, `user_id`, `created_at`, `updated_at`, `image_id`) VALUES (NULL, NULL, NULL, '2011-07-26 00:30:12', '2011-07-26 00:30:12', NULL)
ESC[1mESC[36mSQL (57.1ms)ESC[0m ESC[1mCOMMITESC[0m
Redirected to http://3000/settings?id=12
May not be the "correct" way of doing it but you could probably do this:
In your controller for the update and create method, check what the value of params[:my_setting_attribute] is. You may need to conditionally set the attribute to either "true" or "false".
e.g. perhaps it is returning "1" instead of true (which your log seems to indicuate), then you can set it yourself with something like #my_object.my_setting_attribute = true if params[:my_setting_attribute] == "1". Then probably add an else clause to set everything else to false, just to be safe.

Resources