Unable to update state attribute of the Product model using accepts_nested_attributes. This is what JSON I post looks like:
{"auth_token"=>"x", "product"=>{"caption"=>"x","state_attributes"=>{"id"=>"1"}}, "id"=>"x"}
All I need to do is to change referenced state. Thoughts?
State Model
class State < ActiveRecord::Base
has_many :products
end
Product Model
class Product < ActiveRecord::Base
attr_accessible :state, :state_attributes
belongs_to :state
accepts_nested_attributes_for :state, :allow_destroy => false
end
Products Controller Update Action
def update
product = Product.find_by_id( params[:id])
if product && product.update_attributes(params[:product])
respond_with(product, status: :updated, location: product)
else
respond_with(product.errors, status: :unprocessable_entity)
end
end
Transaction Log
Started PUT "/products/1170.json" for 127.0.0.1 at 2014-01-13 16:21:52 -0700
Processing by ProductsController#update as JSON
Parameters: {"auth_token"=>"x", "product"=>{"caption"=>"x", "state_attributes"=>{"id"=>"3"}}}, "id"=>"1170"}
WARNING: Can't verify CSRF token authenticity
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'x' LIMIT 1
(0.1ms) BEGIN
(0.3ms) UPDATE "users" SET "last_sign_in_at" = '2014-01-13 23:20:46.614453', "current_sign_in_at" = '2014-01-13 23:21:52.251028', "sign_in_count" = 954, "updated_at" = '2014-01-13 23:21:52.251753' WHERE "users"."id" = 536
(6.5ms) COMMIT
Product Load (0.5ms) SELECT "products".* FROM "products" WHERE "products"."user_id" = 536 AND "products"."id" = 1170 LIMIT 1
(0.1ms) BEGIN
State Load (0.2ms) SELECT "states".* FROM "states" WHERE "states"."id" = 2 LIMIT 1
(0.5ms) ROLLBACK
Completed 404 Not Found in 15ms
ActiveRecord::RecordNotFound (Couldn't find State with ID=3 for Product with ID=1170):
app/controllers/products_controller.rb:81:in `update'
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (5.8ms)
As #Sergio Aristizábal pointed out, I was trying to reset associated state instead of simply updating the id
You are trying to reset the id of the associated State. I guess you just want to associate a state to product, so you should just set the state_id attribute.
With that, I updated Product model
class Product < ActiveRecord::Base
attr_accessible :state_id, :state_attributes
belongs_to :state
end
Passed state id in the json
{"auth_token"=>"x", "product"=>{"caption"=>"x","state_id"=>"1"}, "id"=>"x"}
and everything worked like a charm. Thanks #Sergio
Related
i am building an eCommerce app in rails which has two products Chairs and Bookcabinets, i have created two different controllers and models for chairs and bookcabinets, it all worked now i wanted the user to be able to add these products to a cart so i created a ordering system from scratch by watching a tutorial, it worked for chairs but when i add bookcabinets to shopping_cart model it gives me an error: Couldn't find Chair with 'id'=
Server Log
Started POST "/cart/items" for 127.0.0.1 at 2018-09-26 14:16:43 +0530
(0.7ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wGAl7gZGXipKt7EzzZT1LuBgn2k8KnlaPagp0cQ3l6pIkr6mx8MdJAuhgkY7EEttrHjTSSpcRjqe0qZ0a2hrAA==", "bookcabinet_id"=>"1", "quantity"=>"40"}
Chair Load (0.8ms) SELECT "chairs".* FROM "chairs" WHERE "chairs"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 106ms (ActiveRecord: 3.8ms)
ActiveRecord::RecordNotFound (Couldn't find Chair with 'id'=):
app/models/shopping_cart.rb:20:in `add_item'
app/controllers/order_items_controller.rb:8:in `create'
My Order_items_controller
class OrderItemsController < ApplicationController
def index
#items = current_cart.order.items
end
def create
current_cart.add_item(
chair_id: params[:chair_id],
bookcabinet_id: params[:bookcabinet_id],
quantity: params[:quantity]
)
redirect_to cart_path
end
def destroy
current_cart.remove_item(id: params[:id])
redirect_to cart_path
end
end
My Order_controller
class OrdersController < ApplicationController
def new
#order = current_cart.order
end
end
** My Order model**
class Order < ApplicationRecord
has_many :items, class_name: 'OrderItem'
end
My Order_item Model
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :chair
belongs_to :bookcabinet
end
My Shopping_Cart Model
class ShoppingCart
delegate :sub_total, to: :order
def initialize(token:)
#token = token
end
def order
#order ||= Order.find_or_create_by(token: #token) do |order|
order.sub_total = 0
end
end
def items_count
order.items.sum(:quantity)
end
def add_item(chair_id:, bookcabinet_id:, quantity: 1)
chair = Chair.find(chair_id),
bookcabinet = Bookcabinet.find(bookcabinet_id)
order_item = order.items.find_or_initialize_by(
chair_id: chair_id,
bookcabinet_id: bookcabinet_id
)
order_item.price = chair.price
order_item.price = bookcabinet.price
order_item.quantity = quantity
ActiveRecord::Base.transaction do
order_item.save
update_sub_total!
end
end
def remove_item(id:)
ActiveRecord::Base.transaction do
order.items.destroy(id)
update_sub_total!
end
end
private
def update_sub_total!
order.sub_total = order.items.sum('quantity*price')
order.save
end
end
My Create_order migration
class CreateOrders < ActiveRecord::Migration[5.1]
def change
create_table :orders do |t|
t.string :first_name
t.string :last_name, null: false
t.decimal :sub_total, precision: 15, scale: 2, null: false
t.timestamps
end
end
end
my CreateOrderItems migration
class CreateOrderItems < ActiveRecord::Migration[5.1]
def change
create_table :order_items do |t|
t.belongs_to :order, null: false
t.belongs_to :chair, null: false
t.belongs_to :bookcabinet
t.integer :quantity, null: false
t.decimal :price, precision: 15, scale: 2, null: false
t.timestamps
end
end
end
Routes
get '/cart', to: 'order_items#index'
resources :order_items, path: '/cart/items'
get '/cart/checkout', to: 'orders#new', as: :checkout
patch '/cart/checkout', to: 'orders#create'
Add To Cart Form
<div class="button my-2">
<%= form_tag order_items_path do %>
<%= hidden_field_tag :bookcabinet_id, #bookcabinet.id %>
<%= number_field_tag :quantity, 1 %>
<button type="submit" class="btn cart"><i class="d-inline fa fa-cart-arrow-down" aria-hidden="true"></i><p class="d-inline">Add To Cart</p></button>
<% end %>
Updated Server Log
Started POST "/cart/items" for 127.0.0.1 at 2018-09-27 00:24:13 +0530
(0.6ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gqwsV8Z/0p74Y8WPLMmfk9vmoSPCFpP+lAtVxxH3KSvWUzYYIFtbQRkAzM5yh5HS/wAzelr90LJW64joFUpGwg==", "bookcabinet_id"=>"1", "quantity"=>"40"}
Bookcabinet Load (0.7ms) SELECT "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Order Load (0.9ms) SELECT "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ? [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
OrderItem Load (0.5ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? AND "order_items"."chair_id" IS NULL AND "order_items"."bookcabinet_id" = ? LIMIT ? [["order_id", 4], ["bookcabinet_id", 1], ["LIMIT", 1]]
(0.2ms) begin transaction
Bookcabinet Load (0.3ms) SELECT "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.4ms) SELECT SUM(quantity*price) FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
(0.2ms) commit transaction
Redirected to http://localhost:3000/cart
Completed 302 Found in 557ms (ActiveRecord: 10.4ms)
Started GET "/cart" for 127.0.0.1 at 2018-09-27 00:24:14 +0530
Processing by OrderItemsController#index as HTML
Order Load (0.5ms) SELECT "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ? [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
Rendering order_items/index.html.erb within layouts/application
(0.4ms) SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
OrderItem Load (1.1ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
Rendered order_items/index.html.erb within layouts/application (15.0ms)
CACHE (0.1ms) SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
Rendered layouts/_header.html.erb (22.0ms)
Rendered layouts/_footer.html.erb (1.9ms)
Completed 200 OK in 1313ms (Views: 1304.9ms | ActiveRecord: 2.1ms)
You are searching for chair item every time you call add_item method so its throwing an error as you are not passing chair id so you need to modify the method as below
def add_item(chair_id:, bookcabinet_id:, quantity: 1)
chair = Chair.find(chair_id) if chair_id
bookcabinet = Bookcabinet.find(bookcabinet_id) if bookcabinet_id
order_item = order.items.find_or_initialize_by(
chair_id: chair_id,
bookcabinet_id: bookcabinet_id
)
order_item.price = chair.price if chair
order_item.price = bookcabinet.price
order_item.quantity = quantity
ActiveRecord::Base.transaction do
order_item.save
update_sub_total!
end
end
Please feel free to ask if there are any questions regarding the same
I have 2 models: User and Collective, along with their join table, Membership. When a user creates a new collective, I want to simultaneously create a new membership between the two. Right now I have my create function partially working, in that the collective 'new' form adds a collective record to my db but no membership record is added.
User Model
class User < ActiveRecord::Base
has_many :collectives, :through => :memberships
has_many :memberships
end
Collective Model
class Collective < ActiveRecord::Base
has_many :users, :through => :memberships
has_many :memberships
end
Membership Model
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :collective
validates :user_id, presence: true
validates :collective_id, presence: true
end
Collective Controller
def new
#collective = Collective.new if user_signed_in?
end
def create
#collective = Collective.new(collective_params)
if #collective.save
current_user.memberships.create(collective_id: #collective)
flash[:success] = "Collective created!"
redirect_to collective_url(#collective)
else
render 'new'
end
end
private
def collective_params
params.require(:collective).permit(:name, :description, :location, :num_of_users, :num_of_projects)
end
end
Log
Started POST "/collectives" for 127.0.0.1 at 2014-11-06 10:49:39 -0500
Processing by CollectivesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Dh/rG1N6ulrJSIiEaAgudnaltjxnKwCw5sdUQxG9qnE=", "collective"=>{"name"=>"Honda Civic", "location"=>"Cars", "description"=>"Blaahhhhh"}, "commit"=>"Create Collective"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "collectives" ("created_at", "description", "location", "name", "num_of_projects", "num_of_users", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", "2014-11-06 15:49:40.003338"], ["description", "Blaahhhhh"], ["location", "Cars"], ["name", "Honda Civic"], ["num_of_projects", 0], ["num_of_users", 1], ["updated_at", "2014-11-06 15:49:40.003338"]]
(145.3ms) commit transaction
(0.0ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/collectives/7
Completed 302 Found in 208ms (ActiveRecord: 146.7ms)
It seems like the line current_user.memberships.create(collective_id: #collective) is just being ignored for some reason given that the redirect happens fine. Help would be much appreciated. Thanks in advance!
I would say the problem is with passing instance object instead of id. It should be:
if #collective.save
current_user.memberships.create(collective_id: #collective.id)
flash[:success] = "Collective created!"
redirect_to collective_url(#collective)
else
render 'new'
end
Since create method only returns true/false (false in this case because of validation) and does not raise any exception, it gets redirected into show action.
I have found some similar questions on stack overflow, but nothing that helps. I have a user model. I have a profile model that belongs to the user model. I have a job model that belongs to the profile model. I am making a simple form to create a job. When i submit the form in the browser, I am given the error:
undefined method `build_job' for #<Student:0x007f8309023530>
And it shows the create action in the jobs controller:
def create
job = current_user.build_job(job_params)
job.save
redirect_to profile_path(current_user.profile_name)
end
The jobs create method is identical to the profiles create method, with the word profile replaced with job, so I can't figure out why its not working. My guess is it has something to do with jobs belonging to a model that belongs to another model. How do I fix this? Also, here is the job_params method:
def profile_params
params.require(:profile).permit(:title, :category, :description, :state, :zip_code, :rate, jobs_attributes: [:firm, :position])
end
And here are my models:
Job:
class Job < ActiveRecord::Base
belongs_to :profile
end
Profile:
class Profile < ActiveRecord::Base
belongs_to :user
has_many :jobs, :dependent => :destroy
end
User:
class User < ActiveRecord::Base
has_one :profile
end
Reference in view:
<%= #user.profile.job.firm if #user.profile.try(:job)%>
I am also adding my server log from clicking on submit. Hope it helps answer the question:
Started POST "/jobs" for 127.0.0.1 at 2013-10-27 21:45:06 -0400
ActiveRecord::SchemaMigration Load (0.3ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by JobsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VRqIuzR1x6tE/G+/wzrG1iFBOEDE7mgsfyjokX7wNZo=", "job"=>{"firm"=>"signat", "position"=>""}, "commit"=>"Save"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.2ms) BEGIN
SQL (3.4ms) INSERT INTO "jobs" ("created_at", "firm", "position", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Mon, 28 Oct 2013 01:45:06 UTC +00:00], ["firm", "signat"], ["position", ""], ["updated_at", Mon, 28 Oct 2013 01:45:06 UTC +00:00]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/profiles/philip7899
Completed 302 Found in 209ms (ActiveRecord: 9.8ms)
Started GET "/profiles/philip7899" for 127.0.0.1 at 2013-10-27 21:45:06 -0400
Processing by ProfilesController#show as HTML
Parameters: {"id"=>"philip7899"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."profile_name" = 'philip7899' ORDER BY "users"."id" ASC LIMIT 1
Profile Load (0.8ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 ORDER BY "profiles"."id" ASC LIMIT 1 [["user_id", 1]]
School Load (0.9ms) SELECT "schools".* FROM "schools" WHERE "schools"."id" = $1 ORDER BY "schools"."id" ASC LIMIT 1 [["id", 1]]
Job Exists (0.6ms) SELECT 1 AS one FROM "jobs" WHERE "jobs"."profile_id" = $1 LIMIT 1 [["profile_id", 1]]
Rendered profiles/_full_profile.html.erb (92.4ms)
Rendered profiles/show.html.erb within layouts/application (95.4ms)
Rendered layouts/_ssi_header_inner.html.erb (4.2ms)
Rendered layouts/_ssi_footer.html.erb (0.2ms)
Completed 200 OK in 218ms (Views: 209.4ms | ActiveRecord: 5.9ms)
Couple of problems. You need to define has_many jobs on user, and the correct method for building has_many is association.build not build_association:
class User
has_many :jobs, through: :profile
end
job = current_user.jobs.build(job_params)
I have two callbacks that aren't working in my model. They don't raises any error messages either.
The first callback is: after_update :state_closed and I want to use this to close the ticket when I select ticket state from the view 'solved' or 'canceled'. So, I want it in this case is to be closed
The second callback is after_create :assign_state and I want to use this to say the ticket is assigned or its not assigned so if the employee_id is blank thats mean the ticket is not assigned to any employee yet. If employee_id is not black so this ticket is assigned
Here is my ticket.rb
class Ticket < ActiveRecord::Base
before_save :default_values
after_update :state_closed
after_create :assign_state
attr_accessible :description, :title, :employee_department_id, :user_id, :first_name,
:last_name , :email, :state_id, :employee_id, :ticket_state, :assign_state
belongs_to :employee_department
belongs_to :user
belongs_to :state
belongs_to :employee
has_many :replies
def default_values
self.state_id = 3 if self.state_id.nil?
end
def to_label
ticket_state.to_s
end
def state_closed
if self.ticket_state == "Solved" || self.ticket_state == "Canceled"
self.ticket_state = "Closed"
self.save
end
end
def assign_state
if self.employee_id.nil?
self.assign_state = "Un-assigned"
else
self.assign_state = "Assigned"
end
end
Ticket.all.each do |ticket|
if ticket.ticket_state.blank?
ticket.ticket_state = 'open'
end
ticket.save
end
...
This is from server logs when i choose "solved" for example it is updated to "solved" if my callbacks are working then in this case it should change from solved to closed but that's not happening
Started PUT "/tickets/1" for 127.0.0.1 at 2013-09-14 21:46:54 +0200
Processing by TicketsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LZRTSjq9EWqgG6ub3xpd7fioWNtY1SSzy5XQA8ZNep0=", "ticket"=>{"ticket_state"=>"solved"}, "id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
State Load (0.1ms) SELECT "states".* FROM "states"
Ticket Load (0.1ms) SELECT "tickets".* FROM "tickets" WHERE "tickets"."id" = ? LIMIT 1 [["id", "1"]]
(0.0ms) begin transaction
(0.2ms) UPDATE "tickets" SET "ticket_state" = 'solved', "updated_at" = '2013-09-14 19:46:54.926307' WHERE "tickets"."id" = 1
(95.2ms) commit transaction
Redirected to http://localhost:3000/tickets
Completed 302 Found in 100ms (ActiveRecord: 96.0ms)
The issues with each are as follows:
state_closed is not being called because of capitalization issue: "solved" does not equal "Solved". Change the capitalizations to match, or compare the strings when they're both downcased.
assign_state is probably being called, but not persisting because you never actually save the model once it's changed. Try saving after you update on create.
I am trying to create an account management system that allows an account to have one billing address. I want the account and address to have their own controller and model. An admin user would create a new account then be redirected to create a new billing address for this account. The first part works, I am able to create the account, but the second only saves the account_id attribute to the addresses table. Below is my code:
accounts_controller
class AccountsController < ApplicationController
def new
#account = Account.new
end
def create
#account = Account.new(params[:account])
#account.build_address
if #account.save
flash[:success] = "Customer Account has been successfully created!"
redirect_to '/newaddress'
else
render 'new'
end
end
end
addresses_controller
class AddressesController < ApplicationController
def new
#address = Address.new
end
def create
#account = Account.find(params[:account])
#address = #account.create_address(params[:address])
redirect_to root_path
end
end
account_model
class Account < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
attr_accessible :contactFirstName, :contactLastName, :contactEmail, :contactPhone, :business_name
end
address_model
class Address < ActiveRecord::Base
attr_accessible :city, :state, :street, :zipCode
belongs_to :account
end
I also added the following to my routes.rb file
resources :accounts do
resources :addresses
end
Last, below is the schema for the relavant tables
create_table "accounts", :force => true do |t|
t.string "contactEmail"
t.string "contactFirstName"
t.string "contactLastName"
t.string "contactPhone"
t.datetime "joinDate"
t.string "business_name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "addresses", :force => true do |t|
t.string "city"
t.string "state"
t.string "street"
t.string "zipCode"
t.integer "account_id"
t.datetime "created_at"
t.datetime "updated_at"
end
(I am still new to programming and rails so I posted as much as I thought would be relevant.)
Added Log from when I open the new account page and then proceed to the new address page.
Started GET "/newaccount" for 127.0.0.1 at Tue Sep 20 17:21:56 -0500 2011
Processing by AccountsController#new as HTML
Rendered shared/_error_messages.html.erb (0.6ms)
Rendered accounts/_account_fields.html.erb (13.0ms)
Rendered layouts/_stylesheets.html.erb (1.2ms)
User Load (2.5ms) 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 layouts/_header.html.erb (19.4ms)
Rendered layouts/_footer.html.erb (1.0ms)
Rendered accounts/new.html.erb within layouts/application (50.3ms)
Completed 200 OK in 168ms (Views: 64.6ms | ActiveRecord: 2.5ms)
Started POST "/accounts" for 127.0.0.1 at Tue Sep 20 17:22:11 -0500 2011
Processing by AccountsController#create as HTML
Parameters: {"commit"=>"Next", "account"=>{"business_name"=>"FooBar", "contactLastName"=>"Bar", "contactPhone"=>"1231231234", "contactEmail"=>"foo#bar.com", "contactFirstName"=>"Foo"}, "authenticity_token"=>"lJG89TIjcJighmFUWLg1uR9sJq0CHLvceeLH9QNocGY=", "utf8"=>"✓"}
SQL (0.1ms) BEGIN
SQL (0.3ms) SELECT 1 FROM `accounts` WHERE (LOWER(`accounts`.`contactEmail`) = LOWER('foo#bar.com')) LIMIT 1
SQL (1.2ms) describe `accounts`
AREL (0.4ms) INSERT INTO `accounts` (`created_at`, `contactFirstName`, `business_name`, `contactPhone`, `updated_at`, `contactEmail`, `contactLastName`, `joinDate`) VALUES ('2011-09-20 22:22:11', 'Foo', 'FooBar', '1231231234', '2011-09-20 22:22:11', 'foo#bar.com', 'Bar', NULL)
SQL (1.5ms) describe `addresses`
AREL (0.2ms) INSERT INTO `addresses` (`zipCode`, `state`, `city`, `updated_at`, `account_id`, `street`, `created_at`) VALUES (NULL, NULL, NULL, '2011-09-20 22:22:11', 31, NULL, '2011-09-20 22:22:11')
SQL (26.3ms) COMMIT
Redirected to http://localhost:3500/newaddress
Completed 302 Found in 85ms
Started GET "/newaddress" for 127.0.0.1 at Tue Sep 20 17:22:11 -0500 2011
Processing by AddressesController#new as HTML
Rendered addresses/_address_fields.html.erb (83.4ms)
Rendered layouts/_stylesheets.html.erb (1.4ms)
User Load (0.2ms) 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 layouts/_header.html.erb (17.1ms)
Rendered layouts/_footer.html.erb (0.9ms)
Rendered addresses/new.html.erb within layouts/application (113.6ms)
Completed 200 OK in 126ms (Views: 119.6ms | ActiveRecord: 30.3ms)
Started POST "/newaddress" for 127.0.0.1 at Tue Sep 20 17:22:29 -0500 2011
Processing by AddressesController#new as HTML
Parameters: {"address"=>{"city"=>"Boston", "street"=>"123 Main St", "zipCode"=>"02222", "state"=>"MA"}, "commit"=>"Create", "authenticity_token"=>"lJG89TIjcJighmFUWLg1uR9sJq0CHLvceeLH9QNocGY=", "utf8"=>"✓"}
Rendered addresses/_address_fields.html.erb (10.3ms)
Rendered layouts/_stylesheets.html.erb (1.2ms)
User Load (0.2ms) 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 layouts/_header.html.erb (17.2ms)
Rendered layouts/_footer.html.erb (0.9ms)
Rendered addresses/new.html.erb within layouts/application (40.1ms)
Completed 200 OK in 54ms (Views: 47.3ms | ActiveRecord: 0.2ms)
The line in in the Address class looks wrong to me (take out the _attributes):
class Address < ActiveRecord::Base
attr_accessible :city, :state, :street, :zipCode
belongs_to :account
end
As quick look, you are passing only params[:account], tail log and see what you need
class AddressesController < ApplicationController
def new
#address = Address.new
end
def create
#account = Account.find(params[:account])
#address = #account.create_address(params[:address])
redirect_to root_path
end
end
Ass you added log, you can see now that when you post newaddress
Parameters: {"address"=>{"city"=>"Boston", "street"=>"123 Main St", "zipCode"=>"02222", "state"=>"MA"}, "commit"=>"Create", "authenticity_token"=>"lJG89TIjcJighmFUWLg1uR9sJq0CHLvceeLH9QNocGY=", "utf8"=>"✓"}
and your controller have
def create
#account = Account.find(params[:account])
#address = #account.create_address(params[:address])
redirect_to root_path
end
As you can see there are no #account = Account.find(params[:account])
So you account is null, you may add hidden field with account_id to form or catch other way depends of of your app.