Adding items to a cart redirecting wrong - ruby-on-rails

I've been following this Railscast on implementing Active Merchant in a new test app and it was going well, but now that I'm trying to add what I made to my main app its breaking.
When clicking 'add to cart' on my test app, it redirects to the current cart and lists the item as expected.
On my main app clicking the add to cart link redirects to:
http://mainapp.dev/line_items?product_id=1
The line_items controller looks like this:
class LineItemsController < ApplicationController
def create
#product = Product.find(params[:product_id])
#line_item = LineItem.create!(:cart => current_cart, :product => #product, :quantity => 1, :unit_price => #product.price)
flash[:notice] = "Added #{#product.name} to cart."
redirect_to current_cart_url
end
end
The add to cart link looks like this:
<%= link_to "Add to Cart", line_items_path(:product_id => product), :method => :post, :class => "product_actions" %>
edit - logs
Test version on adding an item (working):
Started POST "/line_items?product_id=5" for 127.0.0.1 at 2011-09-01 07:33:27 +0100
Processing by LineItemsController#create as HTML
Parameters: {"authenticity_token"=>"li7gkjksc9MENevuGz7emDwnbB6HrvPAE3CY=", "product_id"=>"5"}
[1m[35mProduct Load (0.4ms)[0m SELECT `products`.* FROM `products` WHERE `products`.`id` = 5 LIMIT 1
[1m[36m (33.1ms)[0m [1mBEGIN[0m
[1m[35mSQL (179.4ms)[0m INSERT INTO `carts` (`created_at`, `purchased_at`, `updated_at`) VALUES ('2011-09-01 06:33:28', NULL, '2011-09-01 06:33:28')
[1m[36m (48.3ms)[0m [1mCOMMIT[0m
[1m[35m (0.2ms)[0m BEGIN
[1m[36mSQL (0.2ms)[0m [1mINSERT INTO `line_items` (`cart_id`, `created_at`, `product_id`, `quantity`, `unit_price`, `updated_at`) VALUES (29, '2011-09-01 06:33:29', 5, 1, 250, '2011-09-01 06:33:29')[0m
[1m[35m (0.5ms)[0m COMMIT
Redirected to http://sell.dev/cart
Completed 302 Found in 1265ms
Started GET "/cart" for 127.0.0.1 at 2011-09-01 07:33:29 +0100
Processing by CartsController#show as HTML
[1m[36mCart Load (0.2ms)[0m [1mSELECT `carts`.* FROM `carts` WHERE `carts`.`id` = 29 LIMIT 1[0m
[1m[35mLineItem Load (0.3ms)[0m SELECT `line_items`.* FROM `line_items` WHERE `line_items`.`cart_id` = 29
[1m[36mProduct Load (0.5ms)[0m [1mSELECT `products`.* FROM `products` WHERE `products`.`id` = 5 LIMIT 1[0m
Rendered carts/show.html.erb within layouts/application (202.1ms)
Rendered layouts/_header.html.erb (0.8ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 368ms (Views: 284.2ms | ActiveRecord: 79.5ms)
The main app version:
Started GET "/line_items?product_id=1" for 127.0.0.1 at 2011-09-01 07:34:59 +0100
Processing by LineItemsController#index as HTML
Parameters: {"product_id"=>"1"}
Rendered line_items/index.html.erb within layouts/application (0.3ms)
Rendered layouts/_header.html.erb (1.3ms)
Rendered layouts/_footer.html.erb (178.4ms)
Completed 200 OK in 218ms (Views: 182.3ms | ActiveRecord: 35.5ms)
I can't figure out why it's wanting to redirect to the line items index and not create, the code is the same.
edit - routes
get "cart" => "carts#show", :as => "current_cart"
resources :orders
resources :line_items
resources :carts
resources :products
resources :order_transactions
edit - taken from my application controller
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_cart
if session[:cart_id]
#current_cart ||= Cart.find(session[:cart_id])
session[:cart_id] = nil if #current_cart.purchased_at
end
if session[:cart_id].nil?
#current_cart = Cart.create!
session[:cart_id] = #current_cart.id
end
#current_cart
end
Thanks for any help its much appreciated!

If you add an item to your cart by clicking on the link "Add to cart" then you will need to call the create action in the LineItemsController controller as you have it now.
The last line of that method is
redirect_to current_cart_url
So you are indeed redirecting to the current_cart as you want but you are saying you are not redirecting to the current cart which is nonsense really.
Perhaps you have not yet set up the current_cart_url path or views or something?
I'm am not clear on what your actual problem is
Started GET "/line_items?product_id=1" for 127.0.0.1 at 2011-09-01 07:34:59 +0100
Processing by LineItemsController#index as HTML
Parameters: {"product_id"=>"1"}
Rendered line_items/index.html.erb within layouts/application (0.3ms)
Rendered layouts/_header.html.erb (1.3ms)
Rendered layouts/_footer.html.erb (178.4ms)
Completed 200 OK in 218ms (Views: 182.3ms | ActiveRecord: 35.5ms)
There MUST be something happening after this! ~What is it?
edit - solution
Sorry, I totally missed the obvious.
<%= link_to "Add to Cart", line_items_path(:product_id => product), :method => :post, :class => "product_actions" %>
is issuing a get request NOT a post request as indicated by your log file Started GET "/cart" for 127.0.0.1 at 2011-09-01 07:33:29 +0100
You are adding an item to the cart which means you are changing state on the server which means you should be using a POST request NOT a get (link) request and therefore you should use a form (button_to will give you that form). Unless you want loads of bot's spiders;/crawlers etc... adding stuff to your cart you should use
<%= button_to 'Add to Cart', line_items_path(:product_id => product) %>

Related

How to handle data with two has_many associations

I'm new to Ruby on Rails. Just getting my head around modelling relationships and how to build CRUD with them. I'd like advice or suggestions on how to fix this problem.
In my system, a support user (student) has private support sessions (like classes) with their support worker (tutor). Here's how the system will be used: a support worker will log in, select a service user they work with, and record a support session, which includes things like how long the session lasted for and where it took place. Eventually, the system will produce time-sheets that can be used to invoice for the tutor's work in these private support sessions.
I'm not quite sure how to interact with this at a controller level. So far I've built my model and scaffolds - now I'm customising them.
I've been using the official tutorial to help me get started at: https://guides.rubyonrails.org/v3.2.8/getting_started.html but I think I've gone beyond that now.
# Models
# Not entirely sure inverse_of is appropriate but several tutorials suggested it's worth putting in
class ServiceUser < ApplicationRecord
has_many :support_sessions, inverse_of: :service_user
has_many :support_workers, through: :support_sessions
end
class SupportWorker < ApplicationRecord
has_many :support_sessions, inverse_of: :support_worker
has_many :service_users, through: :support_sessions
class SupportSession < ApplicationRecord
belongs_to :support_worker, inverse_of: :support_sessions
belongs_to :service_user, inverse_of: :support_sessions
end
# Controller
class SupportSessionsController < ApplicationController
# POST /support_sessions
# POST /support_sessions.json
def create
# Auto-generated line:
#support_session = SupportSession.new(support_session_params)
# Get service_user_id from query string
#service_user = ServiceUser.find(params[:service_user_id])
# Lifted from RoR 'Getting started' article
#support_session = #service_user.support_sessions.create(params[:service_user])
respond_to do |format|
if #support_session.save
#format.html { redirect_to #support_session, notice: 'Support session was successfully created.' }
format.html { redirect_to service_users_url, notice: 'Support session was successfully created.' }
format.json { render :show, status: :created, location: #support_session }
else
format.html { render :new }
format.json { render json: #support_session.errors, status: :unprocessable_entity }
end
end
end
end
# Service user view/HTML form
# This is rendered as a partial on the service user's show.html.erb view
# select_support_workers() helper retrieves a list of ALL support workers in the system and the control value is the support_worker_id
<%= form_for([#service_user, #service_user.support_sessions.build]) do |f| %>
<tr>
<td>
<%= select_support_workers(f) %>
</td>
<td>
<%= f.text_field :location %>
</td>
<td>
<%= f.text_field :mode_of_delivery %>
</td>
<td>
<%= f.text_field :started_at %>
</td>
<td>
<%= f.text_field :ended_at %>
</td>
<td>
<%= f.text_field :total_breaks %>
</td>
<td>
<%= f.submit 'Save session' %>
</td>
</tr>
<% end %>
When I submit the form (which is being rendered as a partial on the service_user view show page), I seem to be ending up in the 'else' part of the if #support_session.save logic.
Error shown in my web browser is:
NameError in SupportSessions#create
Showing /Users/chris/git-local/timesheets/app/views/support_sessions/new.html.erb where line #5 raised:
undefined local variable or method `support_sessions_path' for #<#<Class:0x00007feb3412d028>:0x00007feb34163268>
Did you mean? #support_session
Extracted source (around line #5):
3 <%= render 'form', support_session: #support_session %>
4
5 <%= link_to 'Back', support_sessions_path %>
Rails.root: /Users/chris/git-local/timesheets
Application Trace | Framework Trace | Full Trace
app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb__485411543567831194_70324083953220'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"/xd16JX3LBjA7+9DVfnHwnJziucJkaICaWg/Sd6TK2rDOrugMcZu0r5qr6SO0TfqvXzzhBqvkydMIQqXp2NtrQ==",
"support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""},
"commit"=>"Save session",
"service_user_id"=>"1"}
Console output
Started GET "/service_users/" for ::1 at 2019-05-31 07:58:29 +0100
(0.5ms) SET NAMES utf8, ##SESSION.sql_mode = CONCAT(CONCAT(##sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), ##SESSION.sql_auto_is_null = 0, ##SESSION.wait_timeout = 2147483
↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:29 +0100
Rendering service_users/index.html.erb within layouts/application
(0.6ms) SET NAMES utf8, ##SESSION.sql_mode = CONCAT(CONCAT(##sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), ##SESSION.sql_auto_is_null = 0, ##SESSION.wait_timeout = 2147483
↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
ServiceUser Load (0.7ms) SELECT `service_users`.* FROM `service_users`
Processing by ServiceUsersController#show as HTML
↳ app/views/service_users/index.html.erb:22
Parameters: {"id"=>"4"}
Rendered service_users/index.html.erb within layouts/application (7.6ms)
ServiceUser Load (2.4ms) SELECT `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
↳ app/controllers/service_users_controller.rb:69
Rendering service_users/show.html.erb within layouts/application
SupportSession Load (0.9ms) SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
↳ app/views/service_users/show.html.erb:18
Rendered collection of templates [0 times] (0.0ms)
SupportWorker Load (1.2ms) SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
↳ app/helpers/support_sessions_helper.rb:15
Rendered support_sessions/_form.html.erb (7.5ms)
Rendered service_users/show.html.erb within layouts/application (15.6ms)
Completed 200 OK in 94ms (Views: 91.2ms | ActiveRecord: 0.7ms)
Completed 200 OK in 115ms (Views: 105.7ms | ActiveRecord: 4.5ms)
Started GET "/service_users/" for ::1 at 2019-05-31 07:58:30 +0100
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:30 +0100
Rendering service_users/index.html.erb within layouts/application
Processing by ServiceUsersController#show as HTML
ServiceUser Load (1.5ms) SELECT `service_users`.* FROM `service_users`
Parameters: {"id"=>"4"}
↳ app/views/service_users/index.html.erb:22
Rendered service_users/index.html.erb within layouts/application (5.9ms)
ServiceUser Load (2.2ms) SELECT `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
↳ app/controllers/service_users_controller.rb:69
Rendering service_users/show.html.erb within layouts/application
SupportSession Load (0.8ms) SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
↳ app/views/service_users/show.html.erb:18
Rendered collection of templates [0 times] (0.0ms)
SupportWorker Load (1.3ms) SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
↳ app/helpers/support_sessions_helper.rb:15
Rendered support_sessions/_form.html.erb (5.5ms)
Rendered service_users/show.html.erb within layouts/application (12.1ms)
Completed 200 OK in 126ms (Views: 122.0ms | ActiveRecord: 1.5ms)
Completed 200 OK in 108ms (Views: 100.0ms | ActiveRecord: 4.3ms)
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Processing by ServiceUsersController#show as HTML
Parameters: {"id"=>"4"}
Processing by ServiceUsersController#show as HTML
Parameters: {"id"=>"4"}
ServiceUser Load (1.3ms) SELECT `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
↳ app/controllers/service_users_controller.rb:69
ServiceUser Load (1.5ms) SELECT `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
↳ app/controllers/service_users_controller.rb:69
Rendering service_users/show.html.erb within layouts/application
Rendering service_users/show.html.erb within layouts/application
SupportSession Load (1.5ms) SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
↳ app/views/service_users/show.html.erb:18
SupportSession Load (0.7ms) SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
Rendered collection of templates [0 times] (0.0ms)
↳ app/views/service_users/show.html.erb:18
Rendered collection of templates [0 times] (0.0ms)
SupportWorker Load (1.4ms) SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
↳ app/helpers/support_sessions_helper.rb:15
SupportWorker Load (0.7ms) SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
↳ app/helpers/support_sessions_helper.rb:15
Rendered support_sessions/_form.html.erb (5.7ms)
Rendered service_users/show.html.erb within layouts/application (11.7ms)
Rendered support_sessions/_form.html.erb (5.8ms)
Rendered service_users/show.html.erb within layouts/application (12.6ms)
Completed 200 OK in 80ms (Views: 71.4ms | ActiveRecord: 4.2ms)
Completed 200 OK in 82ms (Views: 74.2ms | ActiveRecord: 2.9ms)
Started POST "/service_users/4/support_sessions" for ::1 at 2019-05-31 07:58:35 +0100
Processing by SupportSessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KZGBtom/9t6vYu5FyPRq3xA3Xmb6hkzG8LEA7c/qmOkUZGmtslduK+l2as5chNz7w4ikC+5fHRYh3Ak2IZwIvA==", "support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""}, "commit"=>"Save session", "service_user_id"=>"4"}
ServiceUser Load (0.5ms) SELECT `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
↳ app/controllers/support_sessions_controller.rb:33
(0.3ms) BEGIN
↳ app/controllers/support_sessions_controller.rb:36
(0.3ms) ROLLBACK
↳ app/controllers/support_sessions_controller.rb:36
(0.2ms) BEGIN
↳ app/controllers/support_sessions_controller.rb:41
(0.2ms) ROLLBACK
↳ app/controllers/support_sessions_controller.rb:41
Rendering support_sessions/new.html.erb within layouts/application
SupportWorker Load (0.5ms) SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
↳ app/helpers/support_sessions_helper.rb:15
Rendered support_sessions/_form.html.erb (3.9ms)
Rendered support_sessions/new.html.erb within layouts/application (324.5ms)
Completed 500 Internal Server Error in 336ms (ActiveRecord: 2.0ms)
ActionView::Template::Error (undefined local variable or method `support_sessions_path' for #<#<Class:0x00007ffb0925c658>:0x00007ffb083fa100>
Did you mean? #support_session):
2:
3: <%= render 'form', support_session: #support_session %>
4:
5: <%= link_to 'Back', support_sessions_path %>
app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb___2840892112036112501_70358075950960'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'
# Crebs:timesheets chris$ rake routes -c support_session
Prefix Verb URI Pattern Controller#Action
service_user_support_sessions GET /service_users/:service_user_id/support_sessions(.:format) support_sessions#index
POST /service_users/:service_user_id/support_sessions(.:format) support_sessions#create
new_service_user_support_session GET /service_users/:service_user_id/support_sessions/new(.:format) support_sessions#new
edit_service_user_support_session GET /service_users/:service_user_id/support_sessions/:id/edit(.:format) support_sessions#edit
service_user_support_session GET /service_users/:service_user_id/support_sessions/:id(.:format) support_sessions#show
PATCH /service_users/:service_user_id/support_sessions/:id(.:format) support_sessions#update
PUT /service_users/:service_user_id/support_sessions/:id(.:format) support_sessions#update
DELETE /service_users/:service_user_id/support_sessions/:id(.:format) support_sessions#destroy
You have nested routes for support_sessions resource, so instead of
<%= link_to 'Back', support_sessions_path %>
you should use code like this to build correct path:
<%= link_to 'Back', [#service_user, :support_sessions] %>
or maybe like this one:
<%= link_to 'Back', service_user_support_sessions_path(#service_user) %>
Here's the code that got things working. Doesn't seem to work very well with validation but the data submits.
def create
#render plain: params[:support_session].inspect
# Auto-generated line:
##support_session = SupportSession.new(support_session_params)
# Get service_user_id from query string
# This is so each new record submitted can get the id of the service_user in question
#service_user = ServiceUser.find(params[:service_user_id])
# Copied from RoR 'Getting started' article: https://guides.rubyonrails.org/getting_started.html
# This calls the create method on #service_user.support_session (rather than #service_user alone)
# so the link is made between the service_user and the support_session
# Calls private method below to safeguard input parameters (only permitted ones)
#support_session = #service_user.support_sessions.create(support_session_params)
#redirect_to service_user_path(#service_user)
respond_to do |format|
if #support_session.save
#if #support_session
#if #service_user.support_sessions.create(support_session_params)
#if #service_user.support_sessions.new(support_session_params)
#format.html { redirect_to #support_session, notice: 'Support session was successfully created.' }
format.html { redirect_to #service_user, notice: 'Support session was successfully created.' }
format.json { render :show, status: :created, location: #support_session }
else
#format.html { render :show }
format.html { redirect_to service_user_path(#service_user), notice: 'There was an error!' }
format.json { render json: #support_session.errors, status: :unprocessable_entity }
end
end
end

How to pass data from view that came from an external API to a controller?

So I want to pass a data from a view that was rendered from an external api to a controller to be able to save the ID to a model/database table.
This is my view:
<h1>Heroes</h1>
<% #response.each do |hero| %>
<div class = "hero_wrap">
<div class = "img">
<img src="https://api.opendota.com<%= hero["img"]%>", id ="hero_img"/>
</div>
<div class = "fave_container">
<%= link_to(image_tag('fave.png', class: "fave_img"), new_hero_path) %>
<%= hero["id"]%>
</div>
<div class = "hero_name">
<%= hero["localized_name"] %>
</div>
</div>
<% end %>
My controller:
# heroes_controller
class HeroesController < ApplicationController
def index
#response = HTTParty.get("https://api.opendota.com/api/heroStats")
end
def create
#hero= Hero.new(params[:id])
#hero.save
redirect_to #hero
end
end
Routes:
Rails.application.routes.draw do
get '/signup', to: 'users#new'
get 'pages/home'
resources :pro_players
devise_for :users
resources :heroes
resources :users
root 'pages#home'
end
My hero model doesn't contain anything yet, I just want to pick the hero id and save it to my database.
this is my web app
server log upon clicking the star icon with link:
Started GET "/heros?custom_hero_id=1&method=post" for 127.0.0.1 at
2018-10-15 09:20:53 +0800
Processing by HerosController#index as HTML
Parameters: {"custom_hero_id"=>"1", "method"=>"post"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳/home/don/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-
5.2.1/lib/active_record/log_subscriber.rb:98
Rendering heros/index.html.erb within layouts/application
Rendered heros/index.html.erb within layouts/application (42.2ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 770ms (Views: 83.3ms | ActiveRecord: 0.7ms)
Updated log:
Started POST "/heros?custom_hero_id=21" for 127.0.0.1 at 2018-10-15 10:13:17 +0800
Processing by HerosController#create as HTML
Parameters: {"authenticity_token"=>"PHDEXdDmPhPX+VdloU2y6yONY5HN5wI2lIfOaSbSKj9+RvTO5Ua3QPuTcreLZtGNDFPaSOXhDVyve6J69+1CQQ==", "custom_hero_id"=>"21"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳/home/don/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
(0.2ms) BEGIN
↳ app/controllers/heros_controller.rb:9
Hero Create (0.4ms) INSERT INTO "heros" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2018-10-15 02:13:17.032248"], ["updated_at", "2018-10-15 02:13:17.032248"]]
↳ app/controllers/heros_controller.rb:9
(42.3ms) COMMIT
↳ app/controllers/heros_controller.rb:9
Redirected to http://localhost:3000/heros/10
Completed 302 Found in 59ms (ActiveRecord: 46.9ms)
Started GET "/heros/10" for 127.0.0.1 at 2018-10-15 10:13:17 +0800
AbstractController::ActionNotFound (The action 'show' could not be found for HerosController):
The :id attribute is by default a auto-increment attribute of datatype integer which sets its value under the hood whenever a new instance of the model is created. There are several ways to override the its behavior or setting its value explicitly, but considering that you are fairly new to the technology I don't recommend those for you. Instead I recommend a simpler solution of using another attribute to store hero["id"]
Steps:
1) Generate a migration to create a new column(say custom_hero_id) in the heroes table
rails g migration add_custom_hero_id_to_heroes custom_hero_id:integer
and do rake db:migrate
2) Change
<%= link_to(image_tag('fave.png', class: "fave_img"), new_hero_path) %>
to
<%= link_to(image_tag('fave.png', class: "fave_img"), heroes_path(custom_hero_id: hero["id"]), method: :post) %>
3) Finally change your create action to below
def create
#hero= Hero.create(custom_hero_id: params[:custom_hero_id])
redirect_to #hero
end
Update:
Due to unknown reason, custom_hero_id isn't saving to the DB. Probably due to forbidden attributes error. Try changing it to
def create
#hero = Hero.new(hero_params)
if #hero.save
redirect_to #hero
end
end
private
def hero_params
params.permit(:custom_hero_id)
end
Do you want to store the hero id or it's name ?
I would advise to create a method in your heroe model. Something like
// heroe.rb
def save_api_heroes_to_db(response)
response.each do |hero|
unless hero[:localized_name].exists?
hero.create(id: hero[:id], name: hero[:localized_name], image: hero[:img])
end
end
end
This method will save the heroe id, name and image in your database (unless it already exists).
You just have to call it in your index method, in your heroe controller.
Hope that helps.

Adding a button on a specific page with backlinks

First post, so i'm a newbie in StackOverflow. I'm trying for several days to make appear a Return button on a page form but only on a specific one.
So, I was advised to use backlink to make it appears.
Here's my code from the form where I want the return button
<% if #backlink.present? %>
<div class="spacer30"></div>
<% if #backlink == 'infos' %>
path = membre_path(menu: 'infos')
<% end %>
<% end %>
<%= link_to "Retour", path, class: "btn-rounded btn-turquoise btn-small" %>
Here's my code controller
def edit
super do |user|
puts "TEST PARAMS BACKLINK #{params[:backlink]}"
#backlink = params[:backlink]
end
end
and my route's :
get 'change_password', to: 'users/registrations#edit'
put 'update' => 'users/registrations#update', :as => 'user_registration'
get 'edit_password', to: 'users/registrations#edit', :as => 'user_edit'
So i should have in my log my PUTS 'TEST PARAMS BACKLINK' but nothing appear, only :
Started GET "/change_password.1?backlink=infos" for ::1 at 2017-10-04 10:07:41 +0200
Processing by Users::RegistrationsController#edit as
Parameters: {"backlink"=>"infos"}
User Load (9.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendering users/registrations/edit.html.erb within layouts/application
Rendered users/registrations/edit.html.erb within layouts/application (14.4ms)
Rendered shared/_navbar.html.erb (4.0ms)
Rendered shared/_flashes.html.erb (1.1ms)
Completed 200 OK in 231ms (Views: 217.0ms | ActiveRecord: 9.1ms)
Any ideas why it doesn't work?
Many thanks.
I just had to delete some lines, here's what i changed from my registration controller :
def edit
#backlink = params[:backlink]
super
end
This way, it appears exactly the way I wanted to.
Many thanks :)

Multiple Users views for signup in Ruby on Rails

I want to create two different signup pages. So from my home view I created these buttons:
<% if not logged_in? %>
<%= link_to "I'm a Hero", signup_path, class: "btn btn-lg btn-primary" %>
<%= link_to "I'm a villain", villain_path, class: "btn btn-lg btn-primary" %>
<% end %>
Now the route obviously looks like this for the "I'm a Hero" button:
get 'signup' => 'users#new'
I can render a nice signup form in views -> user -> new.html.erb. I was thinking that I can do the same for my "I'm a villain" button.
First I wanted to create a new file views -> user -> villain.html.erb. Then I wanted to create a route like this:
get 'villain' => 'users#villain'
If I now click on my "I'm a villain" button, basically nothing happens. And as for localhost:3000/villain, I get redirected to localhost:3000.
What did I miss?
This is the server log when clicking on "Im a villain"
Started GET "/villain" for 130.75.71.234 at 2017-03-11 14:07:00 +0000
Cannot render console from 130.75.71.234! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#villain as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Redirected to https://ruby-project.c9users.io/
Completed 302 Found in 601ms (ActiveRecord: 1.5ms)
Started GET "/" for 130.75.71.234 at 2017-03-11 14:07:01 +0000
Cannot render console from 130.75.71.234! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StaticPagesController#home as HTML
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Rendered static_pages/home.html.erb within layouts/application (4.6ms)
Rendered layouts/_shim.html.erb (0.5ms)
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Rendered layouts/_header.html.erb (2.0ms)
Rendered layouts/_footer.html.erb (0.8ms)
Completed 200 OK in 386ms (Views: 381.7ms | ActiveRecord: 0.5ms)
You need to define the "villain" action in the controller. You probably have the "new" action already defined because you created it through the generator. That is probably why the "new" action does work and not the "villain" one.

Even though I have a scoped nested route, my resources are not routing properly - Rails 3.1

This is my route:
scope ":username" do
resources :feedbacks
end
So when I go to mydomain.com/test/feedbacks/10 it shows the correct feedback with id=10 that belongs to username=test.
But, if I go to mydomain.com/test2/feedbacks/10 it shows me the same feedback with id=10, which does NOT belong to username=test2.
How do I restrict this from happening?
I am using the Vanity gem to give me the username in the URL, this is what that route looks like:
controller :vanities do
match ':vname' => :show, :via => :get, :constraints => {:vname => /[A-Za-z0-9\-\+\#]+/}
end
Edit 1:
That is to say, for clarity's sake, when I go to mydomain.com/test/feedbacks/10 and /test2/feedbacks/10, it shows me the same view for the same record (in which case, the latter version would be wrong because it should be telling me that no such record exists, but it's not. It is just displaying the correct record for test/feedbacks/10).
Edit 2:
Here are the logs of both requests:
The right request
Started GET "/test-3/feedbacks/7" for 127.0.0.1 at 2011-09-14 02:48:15 -0500
Processing by FeedbacksController#show as HTML
Parameters: {"username"=>"test-3", "id"=>"7"}
Feedback Load (0.5ms) SELECT "feedbacks".* FROM "feedbacks" WHERE "feedbacks"."id" = ? LIMIT 1 [["id", "7"]]
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
Rendered feedbacks/show.html.erb within layouts/application (36.2ms)
Completed 200 OK in 188ms (Views: 184.3ms | ActiveRecord: 1.8ms)
The wrong request
Started GET "/test2/feedbacks/7" for 127.0.0.1 at 2011-09-14 02:48:28 -0500
Processing by FeedbacksController#show as HTML
Parameters: {"username"=>"test2", "id"=>"7"}
Feedback Load (0.1ms) SELECT "feedbacks".* FROM "feedbacks" WHERE "feedbacks"."id" = ? LIMIT 1 [["id", "7"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
Rendered feedbacks/show.html.erb within layouts/application (37.6ms)
Completed 200 OK in 50ms (Views: 47.5ms | ActiveRecord: 1.2ms)
Your show action should look something like
def show
#user = User.find_by_username(params[:username])
if #user == current_user
...
render "show"
else
flash[:alert] = "Record doesn't exist"
redirect_to root_path
end
end
I took the liberty of adding in #Benoit's suggestion.

Resources