I have followed a tutorial on how to upload multiple images using active record. I have installed active record, added my associations to my model and when I create a Service (my model) everything seems to be working when I upload 3 images i.e no Active Record errors however I cannot see my images on the FE, all I see is a broken images.
When I go into Rails c and type Service.images.last I can see that images is nil. Does anyone know why this is?
Is there anything else you need to know or see from me?
Thank you
My code to show the image:
<%=#service.images.each do |img| %>
<%= cl_image_tag #service.images, crop: :fill, class: 'card-image', class: 'card-image-show'%>
<%end %>
Rails c
Service Load (59.6ms) SELECT "services".* FROM "services" ORDER BY "services"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<ActiveStorage::Attached::Many:0x00007fffc3ff08a0 #name="images", #record=#<Service id: 14, name: "Test Carpet cleaning", description: "Lorem Ipsum is simply dummy text of the printing a...", picture_url: nil, video: nil, category: "carpet cleaning", created_at: "2019-08-19 12:32:35", updated_at: "2019-08-19 12:32:35", photo: nil, images: nil>, #dependent=:purge_later>
Rails c when i do Service.last.images
irb(main):013:0> Service.last.images
Service Load (0.6ms) SELECT "services".* FROM "services" ORDER BY "services"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<ActiveStorage::Attached::Many:0x00007f92fd1f8780 #name="images", #record=#<Service id: 15, name: "test multiple images", description: "Lorem Ipsum is simply dummy text of the printing a...", picture_url: nil, video: nil, category: "carpet cleaning", created_at: "2019-08-19 18:56:12", updated_at: "2019-08-19 18:56:13", photo: nil, images: nil>, #dependent=:purge_later>
Service model
class Service < ApplicationRecord
has_many_attached :images
mount_uploader :photo, PhotoUploader
end
I would like my 3 images to display on the FE
This is the code that I finally used to get the imageS to show on my SHOW PAGE.
<% if #service.images.attached? %>
<p>
<strong>Images:</strong>
<br>
<% #service.images.each do |image| %>
<%= image_tag(image) %>
<% end %>
</p>
<% end %>
I was using cl_image_tag to display my image which was causing the image to display broken. I should have used the above.
Source:https://evilmartians.com/chronicles/rails-5-2-active-storage-and-beyond
Related
First time I ask a question on this site, hope you can help me for my 'problem'. :-)
Actually, it's not really a problem in development, but in production...
Here's my problem:
I'm working with Rails 3.2.11 and ruby 2.1.7. For this, I'm using RubyMine.
Since the beginning, when I push some data in a hash, the record appears also in an user instance of collection.
I searched in my configuration, in my development.rb, initializers,... But I don't know where it comes! :-(
Because I don't have any reputation on this site, I can't show you what it is, so I will explain it in other way.
I add my User 'Test1' to a tournament via the view by clicking on 'sign in'.
My view (I'm using Haml):
app/views/tournaments/show.html.haml
%p#notice= notice
%p
%b Name:
= #tournament.name
%p
%b Place:
= #tournament.place
= #tournament.to_coordinates
%p
= image_tag "http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{#tournament.latitude}%2C#{#tournament.longitude}"
%p
%b Nb players max:
= #tournament.nb_players_max
- if can? :update, #tournament
= link_to 'Add Match', new_match_path(#tournament.id)
|
= link_to 'Add Games', show_games_path(#tournament.id)
|
= link_to 'Edit', edit_tournament_path(#tournament)
|
= link_to 'Back', tournaments_path
- if #tournament.users.include?(#current_user)
%p
you\'re already signed in for this tournament
- else
= form_for #tournament, url: add_player_path, method: :post do |f|
= f.hidden_field 'tournament_id', :value => #tournament.id
= f.submit 'Sign in'
= link_to 'Seed players', seed_players_path(#tournament.id), method: :post
- if #tournament.users.any?
%ul.list-group
= #tournament.users.each do |player|
%li.list-group-item
= player.pseudo
- else
%p
No players for this tournament.
- if #tournament.games.any?
= #tournament.games.each do |game|
%h2
= game.title
= link_to 'Sign in all players'
- else
%p
No games for this tournament. A new game will be added rapidly.
by clicking on the sign in button, the user is correctly added in #tournament.users. But this appears also in the view just below :
- if #tournament.users.any?
%ul.list-group
= #tournament.users.each do |player|
%li.list-group-item
= player.pseudo
- else
%p
No players for this tournament.
[#<User id: 29, country: "BE", nb_victory: nil, nb_defeat: nil, total_points: nil, created_at: "2016-02-16 14:20:36", updated_at: "2016-02-18 10:07:49", first_name: "T", last_name: "T", pseudo: "Test1", email: "test1#test.com", encrypted_password: "$2a$10$WRHkX0mN0t1GAEYg8CQPJeVHBg0bVzBmDxpHKtU.g23A...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 3, current_sign_in_at: "2016-02-18 10:07:49", last_sign_in_at: "2016-02-17 09:31:06", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: "Q2rJ8aWYPmttd9XRjKgX", confirmed_at: nil, confirmation_sent_at: "2016-02-16 14:20:36", unconfirmed_email: nil, avatar: "chat.png", provider: nil, uid: nil, role: "player">]
In the HTML code, I can see this:
<ul class="list-group">
<li class="list-group-item"> Test1 </li>
[#<User id: 29, country: "BE", nb_victory: nil, nb_defeat: nil, total_points: nil, created_at: "2016-02-16 14:20:36", updated_at: "2016-02-18 10:07:49", first_name: "T", last_name: "T", pseudo: "Test1", email: "test1#test.com", encrypted_password: "$2a$10$WRHkX0mN0t1GAEYg8CQPJeVHBg0bVzBmDxpHKtU.g23A...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 3, current_sign_in_at: "2016-02-18 10:07:49", last_sign_in_at: "2016-02-17 09:31:06", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: "Q2rJ8aWYPmttd9XRjKgX", confirmed_at: nil, confirmation_sent_at: "2016-02-16 14:20:36", unconfirmed_email: nil, avatar: "chat.png", provider: nil, uid: nil, role: "player">]
</ul>
What's wrong with it? It seems a configuration problem.
First: please give a clear problem statement, so that we don't have to guess.
Your problem seem to be that data is written to you html that you don't want. It looks like a ruby-array : [#<User id: 29, country: "BE"....
Is this what is wrong?
Replace the = with a - before #tournament.users.each .
reason: The each call iterates over the array, but also returns the whole array after finishing. If you use a '=', this return value will be written into your html.
MurifoX was right!
Did you change = #tournament.users.each to - #tournaments.users.each?
Of course, if you use '=' in HAML, it's translated like '<%='. But, if we use '-' instead of '=', it's translated like '<%'.
the reason (from Meier):
reason: The each call iterates over the array, but also returns the whole array after finishing. If you use a '=', this return value will be written into your html.
That's it! Thank you everyone :-)
ps: When I can do it, I will up your answers :)
EDIT:
Dave Newton was right too ^^
Really hope this is actually possible but I can't seem to access my forms parameters to send with my custom action
My aim here is for a user to fill in their form, click on a Preview button that will show them what their post will look like, i have created the view which is fine, just passing the parameters is an issue.
This is my current form
# Create Blog Post
form do |f|
inputs 'Blog' do
f.semantic_errors
f.input :title
f.input :category_id, as: :select, collection: Category.all
f.input :comments, as: :text, input_html: { rows: 10, cols: 10 }
f.input :published, as: :boolean
end
inputs 'Submit' do
f.actions do
f.action :submit
f.action :cancel
f.action :reset
li do
link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: "test", comments: 'comments', category_id: '1' }) # Hardcoded for now
end
end
end
end
# Collection Action to handle object
collection_action :preview, method: :get do
#post = Post.new(permitted_params[:post])
end
So with everything the way it is (hardcoded) the params are passed through and output in my preview view, but as soon as i try accessing the forms object/params nothing gets passed th
# Console Output
1 - link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: f.object.title, comments: f.object.comments, category_id: f.object.category_id})
#<Post:0x007f8bbe1fc4c0 id: nil, title: "", comments: "", category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
2 - link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: f.title, comments: f.comments, category_id: f.category_id })
# Console Output
#<Post:0x007f8bbe1fc4c0 id: nil, title: nil, comments: nil, category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
3 - link_to 'Preview', preview_my_admin_panel_posts_path(#post)
# Console Output
#<Post:0x007f8bbe1fc4c0 id: nil, title: nil, comments: nil, category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
Not sure where else to go with this, f.object.param seems close but passing through empty strings? has anyone done this before ?
If anyone has an alternative solution would love to hear it.
Thanks
Update
When outputting params to the console i get this returned
{"action"=>"preview", "controller"=>"my_admin_panel/posts"}
Are you trying to create a post? When you load this page the fields do not have any value thus the link will not load any parameter(you can inspect element on the preview link and see that the link does not have any parameter).
One way is to use JavaScript to catch the value before the link has routed in controller.
How to Rectify this error in RSpec for Controller,
1) SellersController GET index find the Activity
Failure/Error: assigns(:activity).should eq([activity])
expected: [#<Activity id: 65, transactable_type: "admin", transactable_id: 1, action_type: "seller", user_id: 1, is_approved: false, approved_by: nil, created_at: "2012-04-09 11:02:17", updated_at: "2012-04-09 11:02:17", associatable_type: nil, associatable_id: nil>]
got: nil
(compared using ==)
Seller_rspec.rb
describe "GET index" do
it "find the Activity" do
activity = Activity.create!(:transactable_type=>"admin",:transactable_id=>1,:action_type=>"seller",:user_id =>1,:is_approved=>0)
get :index,{:is_approved => activity.to_param,:user_id=>1,:approved_by=>"admin"}
assigns(:activity).should eq([activity])
end
In controller
def index
#activities=Activity.find(:all,:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',:conditions=>["is_approved= ? and user_id=? and approved_by IS NULL",false,current_user.id])
end
You are putting a code into controller which should go to the model. Create a method or scope in Activity model like:
def self.find_not_approved(current_user_id)
find(:all,
:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',
:conditions= ["is_approved= ? and user_id=? and approved_by IS NULL",
false,
current_user_id])
end
So you can just have in controller (I've made up the method name):
def index
#activities = Activity.find_not_appoved(current_user.id)
end
And just to anser your question, it should be assigns(:activities).should eq([activity]) not assigns(:activity).should eq([activity]) - as your are checking #activities variable in controller not, #activity.
Controller:
#users = User.all
View:
<%= #users %>
Result [#<User id: 1, email: "a#a.a", location: "London">, #<User id: 2, email: "b#b.b", location: "Paris">]
How I can add to User class one more pair without adding it to model?
something like:
Controller:
#users.each do |user| <br>
#type = Types.find(:last, :conditions => ["user_id_addressedto = #{user.id}"])
user << #type
end
#users.sort_by(:type)
at the end I want to see result as:
View:
<%= #users %>
Result: [#<User id: 2, email: "b#b.b", location: "Paris", type: "5">, #<User id: 1, email: "a#a.a", location: "London", type: "2">]
class User
# ...
def type
return #type if #type
#type = Types.find(:last, :conditions => ["user_id_addressedto = #{user.id}"])
end
end
This way, it's in the model, but not in the database proper - and it's cached, so it's only queried the first time you need it. That is, only if you need it infrequently enough.
Note: if you are pulling 25 users and reading their type, it's 25 extra SQL calls. Maybe you'd rather make an association, or a scope column.
I'm trying to add an attribute to a model object. Direct access works but when I print the entire object or encode it into JSON, that attribute is left out. Can someone tell me what I'm doing wrong?
Here is my rails console output:
irb(main):010:0> b=ChatMessage.new(:user_id=>4,:room_id=>1,:message=>"Hello World")
=> #<ChatMessage id: nil, room_id: 1, user_id: 4, message: "Hello World", created_at: nil, updated_at: nil>
irb(main):011:0> b.sender_nickname="bbb"
=> "bbb"
irb(main):012:0> b.sender_nickname
=> "bbb"
irb(main):013:0> b
=> #<ChatMessage id: nil, room_id: 1, user_id: 4, message: "Hello World", created_at: nil, updated_at: nil>
Here is my model code:
class ChatMessage < ActiveRecord::Base
attr_accessor :sender_nickname
def self.get_last_message_id
last_message=ChatMessage.all.last
last_message.nil? ? 0 : last_message.id
end
def self.get_all_messages_after(room_id,message_id)
ChatMessage.where("room_id = ? AND id > ?",room_id,message_id)
end
end
edit:
Here is the migration file for chat_messages table.
I'm not really looking to save sender_nickname. So it's more like a virtual attribute (but is still in db through association). And I might need to add other attributes later that aren't in the db. Is it possible to do it without using association?
def self.up
create_table :chat_messages do |t|
t.integer :room_id
t.integer :user_id
t.string :message
t.timestamps
end
end
as far as I know to_json will only take the attributes in the model and serialize (as in chat_message.attributes, not attr_accessor).
You properbly got a sender, or user model, or anything like that.
What I would do is to make a relation to the sender, user or what its called, with a belong_to, and then use this code to convert it to json:
chat_message.to_json(:include => { :sender => { :only => :nickname } })
It may also work with you code, and then just:
chat_message.to_json(:include => { :sender_nickname })
There also some documentation here: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Hope it helps :)