Wicked Gem, associated models param is missing - ruby-on-rails

I have a Boat model and Location Model. Boat has_one :location, Location belongs_to :boat. I used wicked gem to update the models. But I am having an issue in boat_steps_controller's #update action.
Here is my boat_steps_controller,
class BoatStepsController < ApplicationController
include Wicked::Wizard
before_action :logged_in_user
steps :model, :pricing, :description, :picture, :overview, :features, :location
def show
#boat = current_user.boats.find(params[:boat_id])
case step
when :location
#location = #boat.build_location
when :picture
#picture = #boat.pictures.new
#pictures = #boat.pictures.all
end
render_wizard
end
def update
#boat = current_user.boats.find(params[:boat_id])
#boat.update(boat_params)
case step
when :picture
#picture.update(picture_params)
when :location
#location.update(location_params)
end
render_wizard #boat
end
private
def boat_params
params.require(:boat).permit(:brand, :year, :model, .....)
end
def picture_params
params.require(:picture).permit(:name, :boat_id, :image)
end
def location_params
params.require(:location).permit(:address, :longitude, :latitude, :formatted_address, :location_type)
end
end
The problem here is that, in #update action, I update boat_params in every step. But in Location, there is no boat_params to update as it is a associated model. So I have to find a way either get the boat id from the form or put if statement.
Here is the location.html.erb (form for wicked gem)
<%= form_for [#boat, #location], url: wizard_path, method: :put do |f| %>
<div class="field">
<%= f.label :address %><br>
<%= f.text_field :address,:id => "geocomplete", :value => "Ataköy Marina, 34140 Bakırköy/İstanbul, Türkiye" %>
</div>
<div class="field">
<%= f.label :longitude %><br>
<%= f.text_field :longitude, :name => "lng", :readonly => "readonly" %>
</div>
<div class="field">
<%= f.label :latitude %><br>
<%= f.text_field :latitude, :name => "lat", :readonly => "readonly" %>
</div>
<div class="field">
<%= f.label :formatted_address %><br>
<%= f.text_field :formatted_address, :name => "formatted_address", :readonly => "readonly" %>
</div>
<div class="actions">
<%= f.submit "Finish" ,class: "btn btn-primary" %>
</div>
<% end %>
It should normally send boat id as I use [#boat, #location], the url becomes, http://localhost:3000/boats/241/boat_steps/location. But when I post this, I get an error of;
Started PUT "/boats/241/boat_steps/location" for ::1 at 2015-05-12 10:00:21 +0300
Processing by BoatStepsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jJOEBSCe9WdcuMKiHeVnh9zFEYuu15L5tzIkNFo9cED7ToG0MHq8jqeGstq5krdRGnrNXayNTQI0fajjHsNGgQ==", "location"=>{"address"=>"Ataköy Marina, 34140, Bakırköy, İstanbul, Türkiye"}, "lng"=>"28.87443200000007", "lat"=>"40.971388", "formatted_address"=>"Ataköy Marina, 34140 Bakırköy/İstanbul, Türkiye", "commit"=>"Finish", "boat_id"=>"241", "id"=>"location"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Boat Load (0.2ms) SELECT "boats".* FROM "boats" WHERE "boats"."user_id" = ? AND "boats"."id" = ? LIMIT 1 [["user_id", 1], ["id", 241]]
Completed 400 Bad Request in 51ms
ActionController::ParameterMissing (param is missing or the value is empty: boat):
app/controllers/boat_steps_controller.rb:50:in `boat_params'
app/controllers/boat_steps_controller.rb:25:in `update'
And when I erase #boat.update(boat_params) from #update action (which is wrong) but then I receive an error,
NoMethodError (undefined method `update' for nil:NilClass):
app/controllers/boat_steps_controller.rb:32:in `update'

I just put an easy else condition as;
def update
#boat = current_user.boats.find(params[:boat_id])
case step
when :picture
#picture.update(picture_params)
when :location
#location = #boat.build_location
#location.update_attributes(address: params[:location][:address], longitude: params[:lng], latitude: params[:lat])
else
#boat.update(boat_params)
end
render_wizard #boat
end

Related

Couldn't find World with 'id'=

I have a World parent object and a State child object. I'm trying to create a new State object and rails isn't finding the world id. I'm trying to link to the new state form from the world show page, and the url shows .../worlds/1/states/new so why is this not picking up on the parent id? The error is supposedly coming from this line in the controller #world = World.find(params[:id]). I have tried using (params[:world_id]) even.
For brevity I'm only posting the relevant code here.
world.rb
class World < ApplicationRecord
belongs_to :user
has_many :states
end
state.rb
class State < ApplicationRecord
belongs_to :world
belongs_to :user
end
states_controller.rb
class StatesController < ApplicationController
before_action :set_state, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#states = State.all
end
def new
#world = World.find(params[:id])
#state = #world.states.build
end
def create
#world = World.find(params[:id])
#state = #world.states.build(state_params)
#state.user = current_user
respond_to do |format|
if #state.save
format.html { redirect_to #state, notice: 'State was successfully created.' }
else
format.html { render :new }
end
end
end
private
def set_state
#state = State.find(params[:id])
end
def state_params
params.require(:state).permit(:name, :summary, :history, :population, :inception, :life_expectancy, :land_mass,
:climate, :industry, :education, :mythology, :law, :culture, :world_id, :user_id)
end
end
The link to the new state form in worlds/show.html.erb:
<%= link_to 'New State', new_world_state_path(#world) %>
routes.rb
Rails.application.routes.draw do
resources :states
resources :worlds
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
root to: "home#index"
resources :users
resources :worlds do
resources :states
end
end
states/_form.html.erb
<div class="form">
<%= form_for(state) do |f| %>
<% if state.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(world.errors.count, "error") %> prohibited this state from being saved:</h2>
<ul>
<% state.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :name, placeholder: 'Name' %><br />
<fieldset>
<legend>Basic Info</legend>
<%= f.text_area :summary, placeholder: 'Summary About', rows: 6 %><br />
<%= f.text_area :history, placeholder: 'History', rows: 6 %><br />
<%= f.text_area :climate, placeholder: 'Climate', rows: 3 %><br />
<%= f.text_area :industry, placeholder: 'Industry', rows: 3 %><br />
<%= f.text_area :education, placeholder: 'Education', rows: 3 %><br />
<%= f.text_area :culture, placeholder: 'Culture', rows: 3 %><br />
<%= f.text_area :law, placeholder: 'Legal System, Crime & Punishment', rows: 3 %><br />
<%= f.text_area :mythology, placeholder: 'Mythology', rows: 3 %><br />
</fieldset>
<fieldset>
<legend>Quick Stats</legend>
<%= f.text_field :inception, placeholder: 'Inception' %><br />
<%= f.text_field :population, placeholder: 'Population' %><br />
<%= f.text_field :life_expectancy, placeholder: 'Ave. Life Expectance' %><br />
<%= f.text_field :land_mass, placeholder: 'Land Mass' %><br />
</fieldset>
<p><%= f.submit %></p>
<% end %>
</div>
rails console results when clicking 'New State' link
Started GET "/worlds/1/states/new" for 70.196.17.76 at 2017-05-22 13:43:47 +0000
Cannot render console from 70.196.17.76! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StatesController#new as HTML
Parameters: {"world_id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
World Load (0.1ms) SELECT "worlds".* FROM "worlds" WHERE "worlds"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.4ms)
ActiveRecord::RecordNotFound (Couldn't find World with 'id'=):
app/controllers/states_controller.rb:13:in `new'
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (4.7ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.6ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms)
Modify your link_to helper to specify and tell to Rails what's the parameter you're sending through it:
From:
<%= link_to 'New State', new_world_state_path(#world) %>
To:
<%= link_to 'New State', new_world_state_path(id: #world) %>
id because you're trying to find the World through :id as param.
Try also changing the param that's being received within the controller where you're setting the #world variable:
def new
#world = World.find(params[:world_id])
...
end
In the show.html.erb:
<%= link_to 'New World', new_world_state_path(world_id: #world) %>
Update: What we made:
In the app/views/worlds/show.html.erb to change the way the param was being setted:
From:
<%= link_to 'New Nation', new_world_state_path(world_id: #world_id) %> # #world_id wasn't defined
To:
<%= link_to 'New Nation', new_world_state_path(world_id: #world.id) %>
In the /app/views/states/_form.html.erb to add the world_id as a hidden_field:
<%= f.hidden_field :world_id, value: #world.id %>
And then in app/controllers/states_controller.rb to change the way the params were being received:
def new
#world = World.find(params[:world_id])
#state = #world.states.build
end
def create
#world = World.find(params[:state][:world_id])
...
The world_id while it is passed to the :new action, it may not be passed back on the form to the create action.
Your state_params are expecting a :world_id to be sent back so add a hidden field to send it back on the form.
new.html.erb
<%= f.hidden_field :world_id, :value => #world.id %>
and update the create action to
#world = World.find(params[:world_id])

Hidden attribute not populating field in form for Rails 3.2

I'm implementing an invitation system and I want the new user form to pre-populate the user's email address in the email address field on the form (eventually, I will refactor this so it's not a form_field), so that the user doesn't have to type in all their information, just enter a password.
I have created the getter/setter methods in the users.rb model like this:
def invitation_token
invitation.invitation_token if invitation
end
def invitation_token=(invitation_token)
self.invitation = Invitation.find_by_invitation_token(invitation_token)
end
INVITATION MODEL
class Invitation < ActiveRecord::Base
#--== ASSOCIATIONS
belongs_to :sender, :class_name => 'User'
has_one :recipient, :class_name => 'User'
#--== CALLBACKS
before_create :generate_token
before_create :recipient_is_not_registered
before_create :decrement_sender_count, :if => :sender
#--== VALIDATIONS
validates_presence_of :recipient_email
#validate :recipient_is_not_registered
validate :sender_has_invitations, :if => :sender
#--== METHODS
private
def recipient_is_not_registered
if User.find_by_email(recipient_email)
false
else
true
end
end
def sender_has_invitations
unless sender.invitation_limit > 0
redirect_to root_url
end
end
def generate_token #TODO: MOVE to lib/generate_token.rb
self.invitation_token = Digest::SHA1.hexdigest([Time.now, rand].join)
end
def decrement_sender_count
sender.decrement! :invitation_limit
end
end
USER CONTROLLER
class UsersController < ApplicationController
def new
#user = User.new(:invitation_token => params[:invitation_token])
#user.email = #user.invitation.recipient_email if #user.invitation
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
...
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :admin)
end
end
views/users/_form.html.erb
<%= form_for #user do |f| %>
<%= f.hidden_field :invitation_token %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="field">
<%= f.check_box :admin %>
<%= f.label :admin %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
I was following Ryan Bates' RC#124 - Beta Invitations, and got stuck here. His code doesn't produce the error, so I should mention that this is a Rails 3.2.18 app.
When I reload the form, the user's email isn't populated in the form. The relevant log shows:
Started GET "/signup.914823d28d07b747213ec3de47f89ad537169e34" for 127.0.0.1
at 2016-04-30 20:24:47 -0600
Processing by UsersController#new as
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'rOHiKmDcceytxi_t151YIQ' LIMIT 1
Invitation Load (0.0ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."invitation_token" IS NULL LIMIT 1
Rendered users/_form.html.erb (5.0ms)
Rendered users/new.html.erb within layouts/application (6.0ms)
Completed 200 OK in 102.0ms (Views: 25.0ms | ActiveRecord: 3.0ms)
So it appears that the invitation_token isn't being passed in, since the log shows it is NULL.
I have gone over the RC code from top to bottom and can't find out why it's not being passed.
Any help would be appreciated. Thanks.
UPDATE: The output from the view source is:
<input id="user_invitation_token" name="user[invitation_token]" type="hidden" />, so it's not being passed along.
Set the value on the hidden field by passing the value: key:
<%= f.hidden_field :invitation_token, value: some_value %>

Rails ajax form for products

I've been working with app for pizzeria where customers could order pizzas through their website. I currently working with the product page where I try to submit products to shopping cart through ajax, but I'm really stuck. I haven't been able to build a shoppingcart which would accept product-id, product-size-id, extra-toppings as an array and quantity. I decided to try to go with session-store where all the order-row ids are stored and on menu page every product has a form where user could add product, size and quantity to shoppingcart but I keep getting this error in server logs:
Started POST "/order_row" for ::1 at 2015-08-03 11:18:21 +0300
Processing by OrderRowsController#create as JS
Parameters: {"utf8"=>"✓", "order_row"=>{"product"=>"1", "size"=>"0", "quantity"=>"2"}, "commit"=>"Tilaa"}
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms)
ActiveRecord::AssociationTypeMismatch (Product(#70158072501800) expected, got String(#70158039566200)):
app/controllers/order_rows_controller.rb:4:in `create'
I have models Product, ProductCategory, Order, OrderRow and my session stores order-row-ids as mentioned. My menu page is actually product_categories#show -view where products belonging to that category are listed.
#order_rows_controller.rb
class OrderRowsController < ApplicationController
respond_to :html, :js
def create
#orow = OrderRow.new(order_rows_params)
if #orow.save
session[:order_row_ids] << #orow.id
flash[:notice] = "Lisättiin ostoskoriin!"
else
flash[:error] = "Tuotteen lisääminen ostoskoriin epäonnistui."
redirect :back
end
end
def update
#orow = OrderRow.find(params[:id])
if #orow.update_attributes(params[:order_row])
flash[:notice] = "Ostoskori päivitetty."
else
flash[:error] = "Ostoskorin päivitys epäonnistui."
end
end
def destroy
#orow.find(params[:id]).destroy
flash[:notice] = "Tuote poistettu onnistuneesti"
end
private
def order_rows_params
params.require(:order_row).permit(:product, :size, :quantity) #, :extras => []
end
end
ProductCategories-controller
class ProductCategoriesController < ApplicationController
before_action :set_product_category, only: [:edit, :update, :destroy]
respond_to :html, :js
def index
#product_categories = ProductCategory.all
end
def show
#product_category = ProductCategory.friendly.find(params[:id])
#product_categories = ProductCategory.all
#products = #product_category.products
#order_row = OrderRow.new(order: nil, product: nil, size: nil, extras: nil, quantity: nil)
end
And menu-page in product_categories/show.html.erb
#product_categories#show -view
<!--- category descriptions -->
<div class="container">
<% #products.each do |product| %>
<div class="col-sm-6 col-md-4">
<div class="product well">
<h3><%= product.name %></h3>
<span><%= product.description %></span>
<p class="prices">
<%= price(product.normal_price) %> | <%= price(product.plus_size_price) %> | <%= price(product.lunch_price) %>
</p>
<br>
<div id="form-<%= product.id %>">
<%= simple_form_for #order_row, :url => url_for(:controller => 'order_rows', :action => 'create'), remote: true do |f| %>
<%= f.hidden_field :product, :value => product.id %>
<h5>Koko</h5>
<div style="padding-left: 13px">
<%= f.input :size, collection: OrderRow.sizes, as: :radio_buttons, label: false, item_label_class: "radio-inline", item_wrapper_tag: false %>
</div>
<h5>Määrä</h5>
<div style="width: 8%; padding-left: 13px;">
<%= f.input :quantity, as: :string, label: false %>
</div>
<p>
<%= f.submit "Tilaa", class: "btn btn-success btn-lg" %>
</p>
<% end %>
</div>
</div>
</div>
<% end %>
</div>
Create.js.erb in order_rows#create action
#create.js.erb
$("#form-<%= params[:product] %>").load(document.URL + "#form-<%= params[:product]");
Associations:
#order_row
belongs_to :order
belongs_to :product
#product
belongs_to :product_category
has_one :campaign_producte
belongs_to :dish_type
#product_categories
has_many :products
has_many :campaign_products
has_many :product_extras
has_many :dish_types, through: :products
#product_extra
belongs_to :product_category
Link to github-repo: https://github.com/casualCodeAndDesign/ravintolamammamia
What's the reason for this server error and why it doesn't store my order_row to the database?
ActiveRecord::AssociationTypeMismatch (Product(#70158072501800)
expected, got String(#70158039566200))
You need to change
<%= f.hidden_field :product, :value => product.id %>
to
<%= f.hidden_field :product_id, :value => product.id %>
and product to product_id in create.js.erb and order_rows_params

Rails 4 nested forms and strong parameters

I cannot get accepts_nested_attributes_for to work with strong parameters in Rails 4. This is the error
Processing by CityaddressesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Cx9nunLAsHkvo/Z8vKnWFnrub1LpmUgVNdePcQ9VDSQ=", "cityaddress"=>{"st_unit"=>"1", "st_num"=>"1", "st_prefix"=>"E", "name"=>"1", "st_type"=>"ST", "st_postalcode"=>"", "description"=>"", "cityaccount"=>{"name"=>"1", "description"=>"1"}}, "commit"=>"Create Cityaddress"}
[1m[36mUser Load (0.0ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1[0m
Unpermitted parameters: cityaccount
This is the model:
class Cityaddress < ActiveRecord::Base
has_many :cityaccounts
has_many :license_plates
accepts_nested_attributes_for :cityaccounts, allow_destroy: true
def street_address
return "#{st_unit} #{st_num} #{name} #{st_type} #{st_prefix}"
end
def address
return "#{st_unit}#{st_prefix} #{name} #{st_type} #{st_num} "
end
end
This is the controller:
# GET /cityaddresses/new
def new
#cityaddress = Cityaddress.new
#streets = Street.where("active=1").order("display_order")
#cityaddress_accounts = #cityaddress.cityaccounts.build
end
def cityaddress_params
params.require(:cityaddress).permit(:st_unit, :st_num, :st_prefix, :name, :st_type, :st_postalcode, :description, cityaccounts_attributes: [:name, :description, :id])
end
This is the view:
<%= f.fields_for #cityaddress_accounts do |ff| %>
<div class="field">
<%= ff.label :name %>
<%= ff.text_field :name %><br>
</div>
<div class="field">
<%= ff.label :description %>
<%= ff.text_field :description %><br>
</div>
<% end %>
I'm thinking it's something to do with the strong parameter syntax?
Cheers.
I think you have to change the view a bit.
Try changing this
<%= f.fields_for #cityaddress_accounts do |ff| %>
to
<%= f.fields_for :cityaccounts do |ff| %>
Seems all correct, but try in Controller do this:
def new
#cityaddress = Cityaddress.new
#streets = Street.where("active=1").order("display_order")
#cityaddress.cityaccounts.build
end

rails 4 nested forms don't save

I know there's a lot of open questions regarding this around here already but none really helped me.
My main model is being saved properly, all the data is in the post-data, but it just doesn't save the nested models!
Thanks heaps.. Is it anything about the permitted parameters or attr_accessors? Something I suspect.. I didn't really find any documentation on that..
This is my code:
products_controller.rb
def product_params
params.require(:product).permit(:title, :description, :netprice, :vat, :price, :unit_count, :unit, :category, :img, :origin, :originid, :producer, :stock, :discount, :stories_attributes, :origins_attributes, :id)
end
end
def new
#product = Product.new
3.times { #product.stories.build }
#product.origins.build
#categories = []
Category.all.each do |category|
#categories.push([category.name, category.name])
end
end
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render action: 'show', status: :created, location: #product }
else
format.html { render action: 'new' }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
origin.rb
class Origin < ActiveRecord::Base
belongs_to :product
end
product.rb
class Product < ActiveRecord::Base
attr_accessor :stories_attributes, :origins_attributes
has_many :stories
has_many :origins
accepts_nested_attributes_for :stories, allow_destroy:true, :reject_if => lambda { |a| a[:text].blank?}
accepts_nested_attributes_for :origins, allow_destroy:true, :reject_if => lambda {|a| a[:city].blank?}
story.rb
class Story < ActiveRecord::Base
belongs_to :product
end
relevant part of the form
<section class="product-story-section">
<%= f.fields_for :stories do |builder| %>
<fieldset>
<%= builder.label :yindex, "Y-Index" %><br>
<%= builder.text_field :yindex %><br>
<%= builder.label :description, "Story-Text" %><br>
<%= builder.text_area :description %><br>
<%= builder.label :img, "Bild-URL" %><br>
<%= builder.text_field :img %><br>
<%= builder.hidden_field :productid, value:"1" %><br>
</fieldset>
<% end %>
</section>
<hr>
<%= f.fields_for :origins do |builder| %>
<fieldset>
<%= builder.label :city, "Stadt" %><br>
<%= builder.text_field :city %><br>
<%= builder.label :country, "Land" %><br>
<%= builder.text_area :country %><br>
<%= builder.label :geolat, "Geolocation Latitude" %><br>
<%= builder.text_field :geolat %><br>
<%= builder.label :geolng, "Geolocation Longitude" %><br>
<%= builder.text_field :geolng %><br>
</fieldset>
<% end %>
Started POST "/products" for 127.0.0.1 at 2013-12-24 21:01:16 +0100
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"90MXIlzOQg6AcTwwYOkfNsfPuSt1/9UHjqZwHVRnET4=", "product"=> {"title"=>"9", "description"=>"9", "netprice"=>"9", "vat"=>"9", "price"=>"9", "unit_count"=>"9", "unit"=>"9", "img"=>"", "originid"=>"99", "origin"=>"", "producer"=>"9", "stock"=>"9", "discount"=>"9", "stories_attributes"=>{"0"=>{"yindex"=>"9", "description"=>"9", "img"=>"9", "productid"=>"1"}, "1"=>{"yindex"=>"9", "description"=>"9", "img"=>"9", "productid"=>"1"}, "2"=>{"yindex"=>"9", "description"=>"9", "img"=>"9", "productid"=>"1"}}, "origins_attributes"=>{"0"=>{"city"=>"9", "country"=>"", "geolat"=>"9", "geolng"=>"9"}}}, "commit"=>"Create Product"}
Unpermitted parameters: img, productid
Unpermitted parameters: img, productid
Unpermitted parameters: img, productid
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `products` (`created_at`, `description`, `discount`, `img`, `netprice`, `origin`, `originid`, `price`, `producer`, `stock`, `title`, `unit`, `unit_count`, `updated_at`, `vat`) VALUES ('2013-12-24 20:01:16', '9', 9.0, '', 9.0, '', 99, 9.0, '9', 9, '9', '9', 9, '2013-12-24 20:01:16', 9.0)
(0.5ms) COMMIT
Redirected to http://localhost:3000/products/1
Completed 302 Found in 46ms (ActiveRecord: 0.9ms)
New error msg
`attr_accessible` is extracted out of Rails into a gem. Please use new recommended protection model for params(strong_parameters) or add `protected_attributes` to your Gemfile to use old one.
You have an extra end in your product_params method. This should have raised an error.
You also need to add stories and origins attributes to the permit list:
def product_params
params.require(:product).permit(:title, :description, :netprice, :vat, :price, :unit_count, :unit, :category, :img, :origin, :originid, :producer, :stock, :discount, stories_attributes: [:yindex, :description, :image], origins_attributes: [ :city, :country, :geolat], :id)
end
Update: Add missing attributes to the permit list on stories_attributes and origins_attributes:
def product_params
params.require(:product).permit(:title, :description, :netprice, :vat, :price, :unit_count, :unit, :category, :img, :origin, :originid, :producer, :stock, :discount, stories_attributes: [:yindex, :description, :img, :product_id], origins_attributes: [ :city, :country, :geolat, :geolng], :id)
end
Second update:
You also need to update your product model as follows:
class Product < ActiveRecord::Base
attr_accessible :stories_attributes, :origins_attributes
...
end
Replace attr_accessor with attr_accessible. attr_accessible should be used to allow attributes to mass assignment.
In your controller's create action:
# ProductsController
def create
#product = Product.new(product_params)
...
end
Your product_params definitely contains stories_attributes and origins_attributes and are passed to the Product.new method correctly, but because their attributes are not allowed to mass assignment you are not seeing associated stories and origins created. Note that attr_accessor, a Ruby method, only defines getters and setters for the attributes but does not allow for mass assignment.

Resources