Mailboxer Gem Rails 4 - Creating the Views - ruby-on-rails

I'm having difficulty implementing the views for the Mailboxer gem in Rails 4.
So far I have it setup where users can message other users but I don't have anyway for users to see their conversations.
I was getting this error even after I created the partial view: (Trying to copy the views from the example app)
ActionView::Template::Error (Missing partial mailboxer/conversations/_conversation with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:
So i ended up just deleting the views. This is what happens when I send a message:
2.1.1 :004 > User.first.send_message(User.last, "body", "subject")
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "mailboxer_conversations" ("created_at", "subject", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-06-24 17:51:36.131962"], ["subject", "subject"], ["updated_at", "2014-06-24 17:51:36.131962"]]
SQL (0.2ms) INSERT INTO "mailboxer_notifications" ("body", "conversation_id", "created_at", "sender_id", "sender_type", "subject", "type", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["body", "body"], ["conversation_id", 3], ["created_at", "2014-06-24 17:51:36.131962"], ["sender_id", 1], ["sender_type", "User"], ["subject", "subject"], ["type", "Mailboxer::Message"], ["updated_at", "2014-06-24 17:51:36.131962"]]
SQL (0.2ms) INSERT INTO "mailboxer_receipts" ("created_at", "mailbox_type", "notification_id", "receiver_id", "receiver_type", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["created_at", "2014-06-24 17:51:36.222349"], ["mailbox_type", "inbox"], ["notification_id", 3], ["receiver_id", 5], ["receiver_type", "User"], ["updated_at", "2014-06-24 17:51:36.222349"]]
(2.9ms) commit transaction
(0.1ms) begin transaction
SQL (0.8ms) INSERT INTO "mailboxer_receipts" ("created_at", "is_read", "mailbox_type", "notification_id", "receiver_id", "receiver_type", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", "2014-06-24 17:51:36.229168"], ["is_read", "t"], ["mailbox_type", "sentbox"], ["notification_id", 3], ["receiver_id", 1], ["receiver_type", "User"], ["updated_at", "2014-06-24 17:51:36.229168"]]
(0.9ms) commit transaction
(0.3ms) SELECT COUNT(*) FROM "mailboxer_conversation_opt_outs" WHERE "mailboxer_conversation_opt_outs"."conversation_id" = ? AND "mailboxer_conversation_opt_outs"."unsubscriber_type" = 'User' AND "mailboxer_conversation_opt_outs"."unsubscriber_id" = 5 [["conversation_id", 3]]
(0.4ms) SELECT COUNT(*) FROM "mailboxer_notifications" WHERE "mailboxer_notifications"."type" IN ('Mailboxer::Message') AND "mailboxer_notifications"."conversation_id" = ? [["conversation_id", 3]]
=> #<Mailboxer::Receipt id: 6, receiver_id: 1, receiver_type: "User", notification_id: 3, is_read: true, trashed: false, deleted: false, mailbox_type: "sentbox", created_at: "2014-06-24 17:51:36", updated_at: "2014-06-24 17:51:36">

I was having the same problem and I talk to the guy that did the sample app and did the update to 4.1.
You can use that to guide you.
I use it like this:
Controller
def index
#inbox ||= current_user.mailbox.inbox
end
View
<% #inbox.each do |conversation| %>
<%= conversation.originator.username%>
<%= link_to raw(truncate(strip_tags(conversation.subject), :length => 15)), conversation_path(conversation) %>
<%= link_to "", {:controller => "conversations", :action => "trash", :id => conversation.id}, :title=> "Move to Trash", :method=>'post', data: { confirm: '¿Estas seguro?' }, :class=> "btn btn btn-danger icon-remove" %>
<%= conversation.updated_at%>
<% end %>
thats a idea so you can get started.

Related

How do I eliminate this n+1 query?

Models:
class Device < ApplicationRecord
has_many :device_locations
has_many :locations, through: :device_locations do
def previous
order('device_locations.removed_at DESC').first
end
end
end
class Location < ApplicationRecord
has_many :device_locations
has_many :devices, through: :device_locations
end
class DeviceLocation < ApplicationRecord
belongs_to :device
belongs_to :location
end
Controller Action:
# LocationsController
def show
#location = Location.find(params[:id])
#device_locations = #location.device_locations.includes(:device).where(removed_at: nil)
end
View:
<table>
<tr><th>Name</th><th>Install Date</th><th>Uninstall Date</th><th>Previous Location</th></tr>
<%- #device_locations.each do |device_location| %>
<tr>
<td><%= link_to device_location.device.name, device_location.device %></td>
<td><%= device_location.installed_at %></td>
<td><%= device_location.removed_at %></td>
<td><%= link_to device_location.device.locations.previous.name, device_location.device.locations.previous %></td>
</tr>
<% end %>
</table>
The difficulty here is avoiding the n+1 query generated by device_location.device.locations.previous.name. It's like I need to join the table to itself?
Without this column removed from the view the log reads:
Started GET "/locations/1" for ::1 at 2019-08-24 11:09:55 -0400
(0.1ms) SELECT sqlite_version(*)
Processing by LocationsController#show as HTML
Parameters: {"id"=>"1"}
Location Load (0.4ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/locations_controller.rb:69:in `set_location'
Rendering locations/show.html.erb within layouts/application
DeviceLocation Load (14.6ms) SELECT "device_locations".* FROM "device_locations" WHERE "device_locations"."location_id" = ? AND "device_locations"."removed_at" IS NULL [["location_id", 1]]
↳ app/views/locations/show.html.erb:9
Device Load (1.0ms) SELECT "devices".* FROM "devices" WHERE "devices"."id" IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["id", 1], ["id", 5], ["id", 28], ["id", 35], ["id", 51], ["id", 57], ["id", 61], ["id", 86], ["id", 94], ["id", 99], ["id", 107], ["id", 115], ["id", 125], ["id", 139], ["id", 148], ["id", 151], ["id", 159], ["id", 164], ["id", 165], ["id", 168], ["id", 177]]
↳ app/views/locations/show.html.erb:9
Rendered locations/show.html.erb within layouts/application (Duration: 20.7ms | Allocations: 4172)
Completed 200 OK in 25ms (Views: 7.3ms | ActiveRecord: 15.9ms | Allocations: 6079)
With the column present it reads:
Started GET "/locations/1" for ::1 at 2019-08-24 11:10:51 -0400
Processing by LocationsController#show as HTML
Parameters: {"id"=>"1"}
Location Load (0.1ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/locations_controller.rb:69:in `set_location'
Rendering locations/show.html.erb within layouts/application
DeviceLocation Load (0.4ms) SELECT "device_locations".* FROM "device_locations" WHERE "device_locations"."location_id" = ? AND "device_locations"."removed_at" IS NULL [["location_id", 1]]
↳ app/views/locations/show.html.erb:9
Device Load (0.2ms) SELECT "devices".* FROM "devices" WHERE "devices"."id" IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["id", 1], ["id", 5], ["id", 28], ["id", 35], ["id", 51], ["id", 57], ["id", 61], ["id", 86], ["id", 94], ["id", 99], ["id", 107], ["id", 115], ["id", 125], ["id", 139], ["id", 148], ["id", 151], ["id", 159], ["id", 164], ["id", 165], ["id", 168], ["id", 177]]
↳ app/views/locations/show.html.erb:9
Location Load (0.8ms) SELECT "locations".* FROM "locations" INNER JOIN "device_locations" ON "locations"."id" = "device_locations"."location_id" WHERE "device_locations"."device_id" = ? ORDER BY device_locations.removed_at DESC LIMIT ? [["device_id", 1], ["LIMIT", 1]]
↳ app/models/device.rb:5:in `previous'
CACHE Location Load (0.0ms) SELECT "locations".* FROM "locations" INNER JOIN "device_locations" ON "locations"."id" = "device_locations"."location_id" WHERE "device_locations"."device_id" = ? ORDER BY device_locations.removed_at DESC LIMIT ? [["device_id", 1], ["LIMIT", 1]]
↳ app/models/device.rb:5:in `previous'
... N times
CACHE Location Load (0.0ms) SELECT "locations".* FROM "locations" INNER JOIN "device_locations" ON "locations"."id" = "device_locations"."location_id" WHERE "device_locations"."device_id" = ? ORDER BY device_locations.removed_at DESC LIMIT ? [["device_id", 177], ["LIMIT", 1]]
↳ app/models/device.rb:5:in `previous'
Rendered locations/show.html.erb within layouts/application (Duration: 50.7ms | Allocations: 40363)
Completed 200 OK in 55ms (Views: 47.7ms | ActiveRecord: 5.3ms | Allocations: 42252)
Shauno, have you tried the Bullet gem? it helps you get rid of n+1 queries throughout your application by showing a notice at the bottom of pages when a n+1 query is detected, and it also suggests possible solutions.
https://github.com/flyerhzm/bullet
Just make sure to only add it to your development group in the gemfile.

How to save into another table when one table's one record changed from nil to not nil with Rails?

Rails version: 5.2.2.1
Want to insert or update data in post_copies when title data in posts changed from nil to real data.
What I tried:
Model
class Post < ApplicationRecord
after_save :save_post_copy
private
def save_post_copy
if will_save_change_to_title? == nil and saved_change_to_title?
post_copy = PostCopy.find_by(id: self.id)
if post_copy.nil?
PostCopy.create!(id: self.id, title: self.title, body: self.body)
else
post_copy.update!(title: self.title, body: self.body)
end
end
end
end
Console
Case 1: Update from nil to not nil data
post = Post.new
=> #<Post id: nil, title: nil, body: nil, created_at: nil, updated_at: nil>
post.body = 'test'
=> "test"
post.save!
(0.1ms) begin transaction
Post Create (0.9ms) INSERT INTO "posts" ("body", "created_at", "updated_at") VALUES (?, ?, ?) [["body", "test"], ["created_at", "2019-05-20 07:19:50.289983"], ["updated_at", "2019-05-20 07:19:50.289983"]]
(6.5ms) commit transaction
=> true
post.title = '3'
=> '3'
post.save!
(0.1ms) begin transaction
Post Update (0.5ms) UPDATE "posts" SET "title" = ?, "updated_at" = ? WHERE "posts"."id" = ? [["title", "3"], ["updated_at", "2019-05-20 07:20:04.138089"], ["id", 8]]
PostCopy Load (0.1ms) SELECT "post_copies".* FROM "post_copies" WHERE "post_copies"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]]
PostCopy Create (0.3ms) INSERT INTO "post_copies" ("title", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "3"], ["body", "test"], ["created_at", "2019-05-20 07:20:04.148852"], ["updated_at", "2019-05-20 07:20:04.
148852"]]
(7.1ms) commit transaction
=> true
Case 2: Update from not nil to nil data
post
=> #<Post id: 10, title: "ten", body: "10", created_at: "2019-05-20 07:21:08", updated_at: "2019-05-20 07:21:41">
post.title = nil
post.save!
(0.1ms) begin transaction
Post Update (1.4ms) UPDATE "posts" SET "title" = ?, "updated_at" = ? WHERE "posts"."id" = ? [["title", nil], ["updated_at", "2019-05-20 07:34:15.594000"], ["id", 10]]
PostCopy Load (0.1ms) SELECT "post_copies".* FROM "post_copies" WHERE "post_copies"."id" = ? LIMIT ? [["id", 10], ["LIMIT", 1]]
PostCopy Create (0.3ms) INSERT INTO "post_copies" ("body", "created_at", "updated_at") VALUES (?, ?, ?) [["body", "10"], ["created_at", "2019-05-20 07:34:15.598453"], ["updated_at", "2019-05-20 07:34:15.598453"]]
(1.8ms) commit transaction
=> true
Case 3: Update from not nil to not nil(another) data
post
=> #<Post id: 10, title: "ten", body: "10", created_at: "2019-05-20 07:21:08", updated_at: "2019-05-20 07:21:41">
post.will_save_change_to_title?
=> nil
post.title = '1'
=> "1"
post.will_save_change_to_title?
=> true
post.save!
(0.1ms) begin transaction
Post Update (0.6ms) UPDATE "posts" SET "title" = ?, "updated_at" = ? WHERE "posts"."id" = ? [["title", "1"], ["updated_at", "2019-05-20 07:37:46.467899"], ["id", 10]]
PostCopy Load (0.1ms) SELECT "post_copies".* FROM "post_copies" WHERE "post_copies"."id" = ? LIMIT ? [["id", 10], ["LIMIT", 1]]
PostCopy Update (0.3ms) UPDATE "post_copies" SET "title" = ?, "updated_at" = ? WHERE "post_copies"."id" = ? [["title", "1"], ["updated_at", "2019-05-20 07:37:46.471654"], ["id", 10]]
(1.3ms) commit transaction
=> true
Case 2 and case 3 trigger the saving/updating to post_copies action. So the will_save_change_to_title? == nil can't known data change from nil to not nil.
From here:
https://api.rubyonrails.org/classes/ActiveModel/Dirty.html
There are these methods:
person = Person.new
person.changed? # => false
person.name = 'Bob'
person.changed? # => true
person.name_changed? # => true
person.name_changed?(from: nil, to: "Bob") # => true
person.name_was # => nil
person.name_change # => [nil, "Bob"]
person.name = 'Bill'
person.name_change # => [nil, "Bill"]
But seems 'not exists in will_save_change_to_title.
I think your problem is in using "after_save": try using "before_save" instead.
EDIT: Alright, i've tried it as well now, and after i realized it wasn't working, i checked your link: it doesn't look like you've done what is required to implement those methods.
Everything is specified at the top of the page:
The requirements for implementing ActiveModel::Dirty are:
include ActiveModel::Dirty in your object.
Call define_attribute_methods passing each method you want to track.
Call [attr_name]_will_change! before each change to the tracked attribute.
Call changes_applied after the changes are persisted.
Call clear_changes_information when you want to reset the changes information.
Call restore_attributes when you want to restore previous data.
Try following those instructions and the example.

How to pass time_select in controller params?

<%= f.time_select :exact, {ampm: true, :discard_minute=> true} %> # t.time "exact"
How do I pass the above in params?
session[:challenge_exact] = params[:exact].parse_time_select! # got nil error
session[:challenge_exact] = challenge_params[:exact]
session[:challenge_exact] = [params["challenge"]["exact(1i)"], params["challenge"]["exact(2i)"], params["challenge"]["exact(3i)"], params["challenge"]["exact(4i)"], params["challenge"]["exact(5i)"]].join(',')
None of the above work. After the challenge is created I see that exact: nil even though it was populated in the form.
Started POST "/challenges" for ::1 at 2017-05-02 08:28:31 -0400
Processing by ChallengesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oN+DzJK+/GGmpTOOVYMUJQdywuENwxhmX/EVeW6NSZ3w1MctoMd/VHS39d+JasEjHujO88nLPSB2qUKEhet5yA==", "challenge"=>{"name"=>"Write 3 Gratitudes", "categorization"=>"health", "category"=>"goal", "deadline(2i)"=>"6", "deadline(3i)"=>"2", "deadline(1i)"=>"2017", "push"=>"0", "message"=>"1", "mail"=>"0", "remind"=>["mon", "thu", ""], "exact(1i)"=>"2017", "exact(2i)"=>"5", "exact(3i)"=>"2", "exact(4i)"=>"08", "exact(5i)"=>"27", "conceal"=>"0"}, "number"=>"", "email"=>"", "button"=>""}
Redirected to http://localhost:3000/signup
Completed 302 Found in 47ms (ActiveRecord: 0.0ms)
After POST challenge a person then creates a user account...
Started POST "/users" for ::1 at 2017-05-03 01:02:13 -0400
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4Lv5NSfH9tMnC9+t5bVC5x1d571y0jhwsgvYU3t2sp85XAnNOsHk+FCmtGcj2wJVysV6IlAIzF4jCx1hIofwsNg==", "user"=>{"name"=>"test", "last_name"=>"daddy", "email"=>"testdaddy#gmail.com", "password"=>"[FILTERED]", "time_zone"=>"Eastern Time (US & Canada)", "subscribe"=>"0"}, "button"=>""}
(0.2ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testdaddy#gmail.com') LIMIT 1
SQL (2.3ms) INSERT INTO "users" ("time_zone", "name", "last_name", "subscribe", "email", "password_digest", "number", "created_at", "updated_at", "activation_digest", "activated") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id" [["time_zone", "Eastern Time (US & Canada)"], ["name", "test"], ["last_name", "daddy"], ["subscribe", "f"], ["email", "testdaddy#gmail.com"], ["password_digest", "$2a$10$JSSPUl0JDnUXybnAuSnEO.q5DgZscaU3hRpcM4C5L0a0aEtflzb7ne"], ["number", "15169499507"], ["created_at", "2017-05-03 05:02:14.144232"], ["updated_at", "2017-05-03 05:02:14.144232"], ["activation_digest", "$2a$10$NDtWKvxuJm/Hb9YIOzuVIuPpttCZwjsgYws6HhEcbHc.PukxXNpeLa"], ["activated", "t"]]
(18.8ms) COMMIT
(0.2ms) BEGIN
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 16]]
# AS YOU CAN SEE WITH INSERT INTO CHALLENGES FOR SOME REASON THE SESSION PARAMS FOR EXACT ISN'T PASSING FOR EXACT
SQL (0.6ms) INSERT INTO "challenges" ("committed", "name", "categorization", "category", "deadline", "remind", "message", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id" [["committed", nil], ["name", "Write 3 Gratitudes"], ["categorization", "health"], ["category", "goal"], ["deadline", "2017-06-03"], ["remind", "---\n- mon\n- thu\n- ''\n"], ["message", "t"], ["user_id", 16], ["created_at", "2017-05-03 05:02:14.434251"], ["updated_at", "2017-05-03 05:02:14.434251"]]
ActsAsTaggableOn::Tag Load (0.6ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL) [["taggable_id", 40], ["taggable_type", "Challenge"]]
ActsAsTaggableOn::Tag Load (0.8ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND
taggings.tagger_id = 16 AND
taggings.tagger_type = 'User') [["taggable_id", 40], ["taggable_type", "Challenge"]]
(17.2ms) COMMIT
Redirected to http://localhost:3000/
How it appears in console...
exact: 2000-01-01 02:32:00 UTC>
You can access exact params like:
> params[:challenge]["exact(1i)"]
#=> "2017"
> params[:challenge]["exact(2i)"]
#=> "5"
> params[:challenge]["exact(3i)"]
#=> "2"
> params[:challenge]["exact(4i)"]
#=> "08"
> params[:challenge]["exact(5i)"]
#=> "27"
You can parse time like this:
exact_time = "#{params[:challenge]['exact(4i)']}:#{params[:challenge]['exact(5i)']}"
#=> "08:27"
> session[:challenge_exact] = Time.parse(exact_time)
#=> 2017-05-03 08:27:00 +0530
I would do:
session[:challenge_exact] = components_to_absolute(params[:exact])
def components_to_absolute(components)
DateTime.new(components['exact(1i)'].to_i,
components['exact(2i)'].to_i,
components['exact(3i)'].to_i,
components['exact(4i)'].to_i,
components['exact(5i)'].to_i)
end

Preventing multiple POSTS in Ruby on Rails app - Rails 4

I am unsure what is happening.
I have an attending button that user can click to attend an event.
when a user clicks on the attend button i get multiple post request in my terminal
this then displays the user attending the event 3 times
This only happens in the firefox browser
can one kindly tell me how to prevent this?
multiple post displayed in terminal:
Started POST "/attending_socials?social_id=new-members-night-out-west-london" for 127.0.0.1 at 2017-01-27 13:56:26 +0000
Processing by AttendingSocialsController#create as HTML
Parameters: {"authenticity_token"=>"G/9QyoKBaTTsivCKmcKAFO7RoPC6B7Lm6C4G7er2pGYIjYirJwcCUDXCrCoODk5tPl3cRMQUZM6fouQrLnvjRg==", "social_id"=>"new-members-night-out-west-london"}
Social Load (0.1ms) SELECT "socials".* FROM "socials" WHERE "socials"."slug" = ? ORDER BY "socials"."id" ASC LIMIT 1 [["slug", "new-members-night-out-west-london"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 20]]
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "attendances" ("attendable_id", "attendable_type", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["attendable_id", 11], ["attendable_type", "Social"], ["user_id", 20], ["created_at", "2017-01-27 13:56:26.450155"], ["updated_at", "2017-01-27 13:56:26.450155"]]
SQL (0.3ms) INSERT INTO "activities" ("parameters", "key", "owner_id", "owner_type", "trackable_id", "trackable_type", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["parameters", nil], ["key", "attendance.create"], ["owner_id", 20], ["owner_type", "User"], ["trackable_id", 156], ["trackable_type", "Attendance"], ["created_at", "2017-01-27 13:56:26.457301"], ["updated_at", "2017-01-27 13:56:26.457301"]]
(2.9ms) commit transaction
Redirected to http://localhost:3000/socials/new-members-night-out-west-london
Completed 302 Found in 19ms (ActiveRecord: 4.1ms)
Started POST "/attending_socials?social_id=new-members-night-out-west-london" for 127.0.0.1 at 2017-01-27 13:56:26 +0000
Processing by AttendingSocialsController#create as HTML
Parameters: {"authenticity_token"=>"G/9QyoKBaTTsivCKmcKAFO7RoPC6B7Lm6C4G7er2pGYIjYirJwcCUDXCrCoODk5tPl3cRMQUZM6fouQrLnvjRg==", "social_id"=>"new-members-night-out-west-london"}
Social Load (0.2ms) SELECT "socials".* FROM "socials" WHERE "socials"."slug" = ? ORDER BY "socials"."id" ASC LIMIT 1 [["slug", "new-members-night-out-west-london"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 20]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "attendances" ("attendable_id", "attendable_type", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["attendable_id", 11], ["attendable_type", "Social"], ["user_id", 20], ["created_at", "2017-01-27 13:56:26.488498"], ["updated_at", "2017-01-27 13:56:26.488498"]]
SQL (0.3ms) INSERT INTO "activities" ("parameters", "key", "owner_id", "owner_type", "trackable_id", "trackable_type", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["parameters", nil], ["key", "attendance.create"], ["owner_id", 20], ["owner_type", "User"], ["trackable_id", 157], ["trackable_type", "Attendance"], ["created_at", "2017-01-27 13:56:26.497129"], ["updated_at", "2017-01-27 13:56:26.497129"]]
(1.0ms) commit transaction
Redirected to http://localhost:3000/socials/new-members-night-out-west-london
Completed 302 Found in 19ms (ActiveRecord: 2.1ms)
Started POST "/attending_socials?social_id=new-members-night-out-west-london" for 127.0.0.1 at 2017-01-27 13:56:27 +0000
Processing by AttendingSocialsController#create as HTML
Parameters: {"authenticity_token"=>"G/9QyoKBaTTsivCKmcKAFO7RoPC6B7Lm6C4G7er2pGYIjYirJwcCUDXCrCoODk5tPl3cRMQUZM6fouQrLnvjRg==", "social_id"=>"new-members-night-out-west-london"}
Social Load (0.2ms) SELECT "socials".* FROM "socials" WHERE "socials"."slug" = ? ORDER BY "socials"."id" ASC LIMIT 1 [["slug", "new-members-night-out-west-london"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 20]]
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "attendances" ("attendable_id", "attendable_type", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["attendable_id", 11], ["attendable_type", "Social"], ["user_id", 20], ["created_at", "2017-01-27 13:56:27.510657"], ["updated_at", "2017-01-27 13:56:27.510657"]]
SQL (0.1ms) INSERT INTO "activities" ("parameters", "key", "owner_id", "owner_type", "trackable_id", "trackable_type", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["parameters", nil], ["key", "attendance.create"], ["owner_id", 20], ["owner_type", "User"], ["trackable_id", 158], ["trackable_type", "Attendance"], ["created_at", "2017-01-27 13:56:27.516075"], ["updated_at", "2017-01-27 13:56:27.516075"]]
(2.7ms) commit transaction
Redirected to http://localhost:3000/socials/new-members-night-out-west-london
Completed 302 Found in 16ms (ActiveRecord: 3.5ms)
route.rb:
resources :attending_socials, only: [:create, :destroy]
schema:
ActiveRecord::Schema.define(version: 20170121184409) do
create_table "attendances", force: :cascade do |t|
t.integer "attendable_id"
t.string "attendable_type"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "attendances", ["attendable_type", "attendable_id"], name: "index_attendances_on_attendable_type_and_attendable_id"
add_index "attendances", ["user_id"], name: "index_attendances_on_user_id"
end
attendance.rb
class Attendance < ActiveRecord::Base
belongs_to :user
belongs_to :attendable, polymorphic: true
end
attending_socials_controller.rb
class AttendingSocialsController < ApplicationController
before_action :set_social
def create
if Attendance.create(attendable: #social, user: current_user)
redirect_to :back, notice: 'Attending Social'
else
redirect_to :back, alert: 'Something went wrong...*sad panda*'
end
end
def destroy
Attendance.where(attendable_id: #social.id, user_id: current_user.id).first.destroy
redirect_to :back, notice: 'Not Attending Social'
end
private
def set_social
#social = Social.friendly.find(params[:social_id] || params[:id])
end
end
views file:
<div><%= link_to 'Attend testing', attending_socials_path(social_id: #social), method: :post %></div>
You could use this:
Attendance.find_or_create_by(attendable: #social, user: current_user)
given a user can attend each event only once

Ruby on Rails createmethod doesn't work

I got a model day and a model task. day has many tasks. I'm using a nested_form for this. The user enters a time and two variables, which a caculated to an index. The first task, with the highest index has a starttime= 8am.
Now I want to order the tasks by the index and add every task's time to the previous task's starttime.
My attempt to solve this:
def create
#day = current_user.days.build(day_params)
#day.save
#day.tasks.each do |task|
task.index = task.ur**2 + task.imp
end
if current_user.worktype = 1
#tasks = #day.tasks.order(index: :desc)
x = 0
#tasks.each do |task|
if x = 0
task.starttime = Time.new.beginning_of_day + 8*60*60
x = task.id
else
task.starttime = #day.task.find(x).starttime + #day.task.find(x).time*60
x = task.id
end
end
elsif current_user.worktype = 2
...
end
#day.save
respond_to do |format|
if #day.save
format.html { redirect_to #day, notice: 'Day was successfully created.' }
format.json { render :show, status: :created, location: #day }
else
format.html { render :new }
format.json { render json: #day.errors, status: :unprocessable_entity }
end
end
end
But somehow starttime remains nil, when I want to print it out in the view
- #tasks.each do |task|
...
= task.starttime.strftime("%H:%M")
I checked it in rails console too.
consolelog for POST:
Started POST "/days" for ::1 at 2016-08-04 02:19:03 +0200
Processing by DaysController#create as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"YaLq2XBUMltzCpZxvKBp5NQGUgiw/Ockto1r0zy/dZHU3HVlp4lpcsH/b3Q9WYas97ENlwRiPzCUdOiBC06GbA==", "day"=>{"tasks_attributes"=>{"1470269934695"=> {"description"=>"1", "ur"=>"1", "imp"=>"1", "time"=>"1"
, "_destroy"=>"false"}, "1470269939280"=>{"description"=>"2", "ur"=>"3", "imp"=>"3", "time"=>"2", "_destroy"=>"false"}}}, "commit"=>"Create Day"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.0ms) begin transaction
SQL (3.5ms) INSERT INTO "days" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?) [["user_id", 1], ["created_at", "2016-08-04 00:19:03.986762"], ["updated_at", "2016-08-04 00:19:03.986762"]]
SQL (0.0ms) INSERT INTO "tasks" ("description", "ur", "imp", "time", "day_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["description", "1"], ["ur", 1], ["imp", 1], ["time", 1], ["day_id", 11], ["created_at", "2016-08-04 00:19:03.992775"], ["updated_at", "2016-08-04 00:19:03.992775"]]
SQL (0.0ms) INSERT INTO "tasks" ("description", "ur", "imp", "time", "day_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["description", "2"], ["ur", 3], ["imp", 3], ["time", 2], ["day_id", 11], ["created_at", "2016-08-04 00:19:03.994776"], ["updated_at", "2016-08-04 00:19:03.994776"]]
(4.0ms) commit transaction
Task Load (0.5ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."day_id" = ? [["day_id", 11]]
Task Load (0.5ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."day_id" = ? ORDER BY "tasks"."index" DESC [["day_id", 11]]
(0.0ms) begin transaction
SQL (1.0ms) UPDATE "tasks" SET "index" = ?, "updated_at" = ? WHERE "tasks"."id" = ? [["index", 2], ["updated_at", "2016-08-04 00:19:04.006796"], ["id", 24]]
SQL (1.0ms) UPDATE "tasks" SET "index" = ?, "updated_at" = ? WHERE "tasks"."id" = ? [["index", 12], ["updated_at", "2016-08-04 00:19:04.009792"], ["id", 25]]
(3.6ms) commit transaction
(0.0ms) begin transaction
(0.0ms) commit transaction
Redirected to http://localhost:3000/days/11
Completed 302 Found in 39ms (ActiveRecord: 14.6ms)
EDIT
Building on #evanbike's answer I added a task.save everytime starttime is set. But nothing changed, so I tried and removed the If statement and now starttime is saved, but every task has the same time.
#tasks = #day.tasks.order(index: :desc)
x = 0
#tasks.each do |task|
if x = 0
task.starttime = Time.new.beginning_of_day + 8*60*60
task.save
x = task.id
else
task.starttime = #day.task.find(x).starttime + #day.task.find(x).time*60
task.save
x = task.id
end
end
#day.save
I hope someone can help me with this issue.
Thanks in advance.
When you do this, you are setting the index on the instance of the task in the #day association cache:
#day.tasks.each do |task|
task.index = task.ur**2 + task.imp
end
Then, when you do this:
#tasks = #day.tasks.order(index: :desc)
...it makes a db call (since you're calling order on it) and return new instances—that don't have index set. If you called sort or some array method, it would use the stored instances
I think the simplest would be to save the instances of tasks after you set each of the values. Calling sort on the association would probably work, but it seems brittle.

Resources