Ruby on Rails createmethod doesn't work - ruby-on-rails

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.

Related

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.

Rails not including attribute in SQL Query even though specified

Despite providing the name, the SQL query clearly shows that it's not being passed properly. Rails console doesn't require any whitelist parameters as far as I'm aware, but I've included my controller as well.
Query in rails console: Profession.first.skills.create(name: 'rails')
Profession Load (0.5ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.2ms) BEGIN
Skill Exists (0.4ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
SQL (1.0ms) INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["profession_id", 1], ["created_at", "2017-12-18 12:22:11.154775"], ["updated_at", "2017-12-18 12:22:11.154775"]]
(0.1ms) ROLLBACK
Not sure what's going on here.
Validation errors are still working though...
Valid object:
:027 > Skill.new(name: "rails", profession: Profession.first).valid?
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
Skill Exists (1.9ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
=> true
Name being detected for validations:
:020 > Skill.create!(name: String.new, profession: Profession.first)
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.1ms) BEGIN
Skill Exists (0.4ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", ""], ["LIMIT", 1]]
(0.1ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
from (irb):20
Max Length:
:023 > Skill.create!(name: "sjadfkahskdfkjsahdfkjaskjdfkjhsdjkfhksajhfjksahasdljflasjdlfkjaskldjflkasjdklfjklasjdklfjlasjdflkjasklfjsdfhkjsahkjdfhjkasdhfkjhkj", profession: Profession.first)
Profession Load (0.4ms) SELECT "professions".* FROM "professions" ORDER BY "professions"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.2ms) BEGIN
Skill Exists (0.3ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "sjadfkahskdfkjsahdfkjaskjdfkjhsdjkfhksajhfjksahasdljflasjdlfkjaskldjflkasjdklfjklasjdklfjlasjdflkjasklfjsdfhkjsahkjdfhjkasdhfkjhkj"], ["LIMIT", 1]]
(0.3ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Name is too long (maximum is 50 characters)
from (irb):23
ProfessionsController
class ProfessionsController < ApplicationController
def new
#profession = Profession.new
end
def create
#profession = Profession.find_by(name: profession_params[:name])
skill_params = get_nested_params(profession_params, :skills_attributes)
if #profession
# Save skill under existing profession
#skill = Skill.create(name: skill_params[:name], profession_id: #profession.id)
else
#profession = Profession.new(name: profession_params[:name])
if #profession.save {
saved_profession = Profession.find_by(name: profession_params[:name])
saved_profession.skills.create(name: "twitter")
# Skill.create(name: skill_params[:name], profession_id: Profession.find_by(name: profession_params[:name])).save!
}
end
end
respond_to do |format|
if #profession.save || #skill.save
format.js { render layout: false }
format.html { redirect_back fallback_location: root_path, notice: 'Profession was successfully created.' }
else
format.html { redirect_back fallback_location: root_path, notice: 'Skill was not created.' }
end
end
end
private
def profession_params
params.require(:profession).permit(:name,
skills_attributes: [:id,
:name,
:starting_date,
:profession_id,
:_destroy])
end
def get_nested_params parent_params, nested_params
nested_attrs = parent_params[nested_params]
nested_attrs[nested_attrs.keys[0]]
end
end
Updated:
Error from controller when using saved_profession.skills.create(name: "twitter")
Started POST "/professions" for 127.0.0.1 at 2017-12-19 01:50:50 +1300
Processing by ProfessionsController#create as JS
Parameters: {"utf8"=>"✓", "profession"=>{"name"=>"software", "skills_attributes"=>{"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}}, "commit"=>"Create Profession"}
Profession Load (0.3ms) SELECT "professions".* FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
(0.1ms) BEGIN
Profession Exists (0.3ms) SELECT 1 AS one FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "professions" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "software"], ["created_at", "2017-12-18 12:50:50.202270"], ["updated_at", "2017-12-18 12:50:50.202270"]]
Profession Load (0.2ms) SELECT "professions".* FROM "professions" WHERE "professions"."name" = $1 LIMIT $2 [["name", "software"], ["LIMIT", 1]]
Skill Exists (0.3ms) SELECT 1 AS one FROM "skills" WHERE "skills"."name" = $1 LIMIT $2 [["name", "twitter"], ["LIMIT", 1]]
SQL (0.7ms) INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["profession_id", 4], ["created_at", "2017-12-18 12:50:50.205484"], ["updated_at", "2017-12-18 12:50:50.205484"]]
(0.1ms) ROLLBACK
Completed 500 Internal Server Error in 8ms (ActiveRecord: 2.2ms)
ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint
DETAIL: Failing row contains (11, null, 2017-12-14, 4, 2017-12-18 12:50:50.205484, 2017-12-18 12:50:50.205484, null).
: INSERT INTO "skills" ("profession_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"):
app/controllers/professions_controller.rb:21:in `block in create'
app/controllers/professions_controller.rb:18:in `create'
Try modifying your get_nested_params as:
def get_nested_params(parent_params, nested_params)
parent_params # For logging purpose only
# => {"name"=>"software", "skills_attributes"=>{"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}}
nested_params # For logging purpose only
# => :skills_attributes
nested_attrs = parent_params[nested_params]
# => {"1513601431887"=>{"name"=>"rails", "_destroy"=>"false"}}
nested_attrs.values[0] # Return this
# => {"name"=>"rails", "_destroy"=>"false"}
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

How to change default boolean value via submit button?

The user can choose of one of two submit buttons. If he clicks <%= f.submit :conceal %> how can the default value be made to change from false to true?
t.boolean "conceal", default: false
because right now if the user clicks the button - the default value remains false:
[1] pry(main)> Valuation.find(9)
Valuation Load (0.2ms) SELECT "valuations".* FROM "valuations" WHERE "valuations"."id" = ? LIMIT 1 [["id", 9]]
=> #<Valuation:0x007fdf26c736b8
id: 9,
conceal: false,
user_id: 1,
created_at: Thu, 23 Apr 2015 16:21:31 UTC +00:00,
updated_at: Thu, 23 Apr 2015 16:21:31 UTC +00:00,
likes: nil,
name: "Conceal/Private/Hide">
This didn't work <%= f.submit :conceal => true %>.
class ValuationsController < ApplicationController
before_action :set_valuation, only: [:show, :edit, :update, :destroy, :like]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
#valuations = Valuation.tagged_with(params[:tag])
else
#valuations = Valuation.order('RANDOM()')
end
end
def show
#valuation = Valuation.find(params[:id])
#commentable = #valuation
#comments = #commentable.comments
#comment = Comment.new
end
def new
#valuation = current_user.valuations.build
end
def edit
end
def create
#valuation = current_user.valuations.build(valuation_params)
if #valuation.save
track_activity #valuation
redirect_to #valuation, notice: 'Value was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
def update
if #valuation.update(valuation_params)
track_activity #valuation
redirect_to #valuation, notice: 'Value was successfully updated'
else
render action: 'edit'
end
end
def destroy
#valuation.destroy
redirect_to valuations_url
end
def like
without_tracking do
#valuation.increment!(:likes)
end
#valuation.create_activity :like
flash[:success] = 'Thanks for sharing your Value!'
redirect_to valuation_path(#valuation)
end
private
def without_tracking
Valuation.public_activity_off
yield if block_given?
Valuation.public_activity_on
end
def set_valuation
#valuation = Valuation.find(params[:id])
end
def correct_user
#valuation = current_user.valuations.find_by(id: params[:id])
redirect_to valuations_path, notice: "Not authorized to edit this valuation" if #valuation.nil?
end
def valuation_params
params.require(:valuation).permit(:name, :conceal, :tag_list, :content, :commentable, :comment, :like)
end
end
UPDATE
Started POST "/valuations" for 127.0.0.1 at 2015-04-23 15:27:35 -0400
Processing by ValuationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xd4ISNLZxjryLJfxvauWUANBzJthCNBzUwhtxseB/ird77mdYoKY/f9Skzb68lClaWOIUJXie9qC0jI1l+d98w==", "valuation"=>{"name"=>"PRIVATE AGAIN", "tag_list"=>""}, "commit"=>"conceal"}
[1m[36mUser Load (0.7ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1[0m [["id", 1]]
[1m[35mHabit Load (0.2ms)[0m SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ? [["user_id", 1]]
[1m[36mHabit Load (0.2ms)[0m [1mSELECT "habits".* FROM "habits"[0m
[1m[35mActsAsTaggableOn::Tag Load (0.2ms)[0m SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35mSQL (31.7ms)[0m INSERT INTO "valuations" ("name", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "PRIVATE AGAIN"], ["user_id", 1], ["created_at", "2015-04-23 19:27:36.015267"], ["updated_at", "2015-04-23 19:27:36.015267"]]
[1m[36mActsAsTaggableOn::Tag Load (0.1ms)[0m [1mSELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)[0m [["taggable_id", 15], ["taggable_type", "Valuation"]]
[1m[35m (10.8ms)[0m commit transaction
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35mSQL (1.7ms)[0m INSERT INTO "activities" ("action", "trackable_id", "trackable_type", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["action", "create"], ["trackable_id", 15], ["trackable_type", "Valuation"], ["user_id", 1], ["created_at", "2015-04-23 19:27:36.136688"], ["updated_at", "2015-04-23 19:27:36.136688"]]
[1m[36m (1.5ms)[0m [1mcommit transaction[0m
Redirected to http://0.0.0.0:3000/valuations/15
The submit method takes an argument for what name it will show up as, but that's only useful for determining which button, if there's more than one, was used to submit the form.
What you want to do is introduce a hidden field that has the right naming convention so you can use update_attributes, or you need to test for the presence of params[:commit] which, if present, means someone pressed that button:
if (params[:commit] == 'conceal')
#valuation.conceal = true
end

Mailboxer Gem Rails 4 - Creating the Views

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.

Resources