I'd like users to be able to create a User System with multiple existing Parts. That it. Currently when I edit or create a user system with a part select I get.
Processing by UserSystemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LgudsjWoAROXi0DGpUaH0ie2GNAuooRGtsPN+fOg+Gtev6Q6QmJC4dYIwFW9evaBOa0TUWotrQec1o1ROCbwFQ==", "user_system"=>{"name"=>"adfa"}, "parts_user_systems"=>{"part_id"=>["", "2", "3"]}, "button"=>""}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 101]]
(0.1ms) BEGIN
SQL (0.6ms) INSERT INTO "user_systems" ("name", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["name", "adfa"], ["user_id", 101], ["created_at", "2015-07-10 17:10:39.564555"], ["updated_at", "2015-07-10 17:10:39.564555"]]
(0.2ms) COMMIT
Nothing get's submitted to the join table.
class UserSystem < ActiveRecord::Base
has_many :parts_user_systems, foreign_key: "part_id"
has_many :parts, through: :parts_user_systems, foreign_key: "part_id"
end
class Part < ActiveRecord::Base
has_many :parts_user_systems
has_many :user_systems, through: :parts_user_systems
end
class PartsUserSystem < ActiveRecord::Base
belongs_to :part
belongs_to :user_system
end
class UserSystemsController < ApplicationController
def user_system_params
params.require(:user_system).permit(:name, :user_id, part_ids: [:ids])
end
end
_form.html.erb
<%= form_for(#user_system) do |f| %>
<div class="field">
<%= f.label :part_id, "Part " %><br/>
<%= collection_select :parts_user_systems, :part_id, Part.all, :id, :name, {:selected => 1}, {:multiple => true} %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
</div>
<% end %>
show.html.erb
<%= #user_system.parts.each do |part| %>
<li><%= part.name%> by by <%= part.parts_user_system%></li></li>
<% end %>
Related
All help/hints/debugging tips/thoughts are welcome, as I'm pretty much stuck for some time on this issue.
I have a 2-level deep nested form. The parameters of the 1st level are saving correctly (e.g. options_attributes), but unfortunately the parameters of the deepest form are not being sent to the controller (.e.g. option_prices_attributes is not shown at all in my parameters. I use the cocoon gem to create a dynamic nester form.
Interestingly,
(1) in my console I am able to create a 2-level deep object where also the option_price parameters are saving.
(2) when using :option_prices_attributes in the simple_field forms, they are being sent as parameters:
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"P6oCZkZF8O+, "accommodation_category"=>{"options_attributes"=>{"1568305809712"=>{"name"=>"Option name", "_destroy"=>"false", "option_prices_attributes"=>{"name"=>"Option price", "_destroy"=>"0"}}}}, "commit"=>"Save", "park_id"=>"8", "id"=>"96"}
=> and consequently resulting in an error message in the terminal saying
no implicit conversion of Symbol into Integer
My models
class AccommodationCategory < ApplicationRecord
belongs_to :park
has_many :options, dependent: :destroy
accepts_nested_attributes_for :options, allow_destroy: true
end
class Option < ApplicationRecord
belongs_to :accommodation_category
has_many :option_prices, dependent: :destroy
accepts_nested_attributes_for :option_prices, allow_destroy: true
end
class OptionPrice < ApplicationRecord
belongs_to :option
end
Accommodation_categories_controller.rb
class AccommodationCategoriesController < ApplicationController
# skip_before_action :authenticate_user!
[...]
def update
#park = Park.find(params[:park_id])
#accommodation_category = #park.accommodation_categories.find(params[:id])
authorize #accommodation_category
#accommodation_category = #accommodation_category.update_attributes(accommodation_category_params)
end
def new_options
#accommodation_category = AccommodationCategory.find(params[:id])
#park = #accommodation_category.park
authorize #accommodation_category
#2nd level nesting
# #accommodation_category.options.build
#accommodation_category.options.each do |option|
option.option_prices.build
end
end
private
def accommodation_category_params
params.require(:accommodation_category).permit(:name, :description, :status, :persons_max, :persons_min, :persons_included, :accommodation_count, :enabled_accommodation_count, :thumb, :included_services, :photo,
options_attributes: [:name, :description, :_destroy,
option_prices_attributes: [:name, :price_type, :start_date, :end_date, :price, :duration, :duration_min, :duration_max, :backend_only, :weekend_extra, :_destroy]])
end
end
views/accommodation_categories/new_options.html.erb
<%= render 'options_new_form', park: #park%>
views/accommodation_categories/options_new_form.html.erb (1st level)
<%= simple_form_for [#park, #accommodation_category] do |f|%>
<h1> <%= #accommodation_category.name %> </h1>
<% #accommodation_category.options.each do |option| %>
<%= option %>
<% end %>
<%= f.simple_fields_for :options do |option| %>
<%= render 'option_fields', f: option %>
<% end %>
<div>
<%= link_to_add_association 'add option', f, :options %>
</div>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
views/accommodation_categories/option_fields.html.erb (2nd level)
<%= f.input :name %>
<%= f.check_box :_destroy %>
<%= link_to_remove_association "remove option", f %>
<%= f.simple_fields_for :option_prices do |option_price| %>
<%= render 'option_price_fields', f: option_price %>
<% end %>
<%= link_to_add_association 'add option price', f, :option_prices %>
views/accommodation_categories/option_price_fields.html.erb
<%= f.input :name %>
<%= f.check_box :_destroy %>
<%= link_to_remove_association "remove option price", f %>
The message in my terminal when sending the parameter to the controller is the following:
Processing by AccommodationCategoriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"QlROXu9ImP6GSvPJQgd7eVZtaWsiVT6myWzZEFIEtEulSrQmt75XVMEI/avKUzhjZaZG9Kj0Pmih6J/4UYO8IQ==", "accommodation_category"=>{"options_attributes"=>{"1568290804865"=>{"name"=>"option name", "_destroy"=>"false"}}}, "commit"=>"Save", "park_id"=>"8", "id"=>"93"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /Users/xx/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Park Load (0.4ms) SELECT "parks".* FROM "parks" WHERE "parks"."id" = $1 LIMIT $2 [["id", 8], ["LIMIT", 1]]
↳ app/controllers/accommodation_categories_controller.rb:29
AccommodationCategory Load (0.2ms) SELECT "accommodation_categories".* FROM "accommodation_categories" WHERE "accommodation_categories"."park_id" = $1 AND "accommodation_categories"."id" = $2 LIMIT $3 [["park_id", 8], ["id", 93], ["LIMIT", 1]]
↳ app/controllers/accommodation_categories_controller.rb:30
(0.2ms) BEGIN
↳ app/controllers/accommodation_categories_controller.rb:32
Option Create (0.3ms) INSERT INTO "options" ("accommodation_category_id", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["accommodation_category_id", 93], ["name", "option name"], ["created_at", "2019-09-12 12:20:14.265335"], ["updated_at", "2019-09-12 12:20:14.265335"]]
↳ app/controllers/accommodation_categories_controller.rb:32
(0.7ms) COMMIT
↳ app/controllers/accommodation_categories_controller.rb:32
AccommodationCategory Load (0.2ms) SELECT "accommodation_categories".* FROM "accommodation_categories" WHERE "accommodation_categories"."park_id" = $1 AND "accommodation_categories"."id" = $2 LIMIT $3 [["park_id", 8], ["id", 93], ["LIMIT", 1]]
↳ app/controllers/accommodation_categories_controller.rb:45
Redirected to http://localhost:3000/accommodation_categories/93/new_discounts
Completed 302 Found in 14ms (ActiveRecord: 2.3ms)
None of your nested-fields partials seem to have a wrapper-class? Cocoon explicitly relies on a specific mark-up, this could cause e.g. the nested fields to appear to be inserted correctly, but inserted outside of the form and then of course never posted to the server/controller.
I get some error to insert following_id, then i checked the development.log:
This is my false: follower_id = nil
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 9]]
[1m[36mUser Load (1.0ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1[0m [["id", "11"]]
[1m[36mSQL (3.0ms)[0m [1mINSERT INTO "relations" ("created_at", "follower_id", "following_id", "updated_at") VALUES (?, ?, ?, ?)[0m [["created_at", Thu, 23 Oct 2014 07:19:22 UTC +00:00], ["follower_id", nil], ["following_id", 11], ["updated_at", Thu, 23 Oct 2014 07:19:22 UTC +00:00]]
I wan it to become: follower_id = 9, change between line 1 and 2
[1m[36mUser Load (0.0ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1[0m [["id", "9"]]
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "11"]]
[1m[36mSQL (3.0ms)[0m [1mINSERT INTO "relations" ("created_at", "follower_id", "following_id", "updated_at") VALUES (?, ?, ?, ?)[0m [["created_at", Thu, 23 Oct 2014 07:19:22 UTC +00:00], ["follower_id", 9], ["following_id", 11], ["updated_at", Thu, 23 Oct 2014 07:19:22 UTC +00:00]]`
So,How can i change it to be true???Some thing wrong with my code??Please help me!
*This is my User model
class User < ActiveRecord::Base
attr_accessible :pass, :username
# Who am I following?
has_many :relations, :foreign_key => :follower_id
has_many :following, :through => :relations
# Who am I followed by?
has_many :relations, :class_name => "Relation", :foreign_key => :following_id
has_many :followers, :through => :relations
validates :username, :pass, :presence => true
validates :username, :pass, :length => { :minimum => 4 }
validates :username, :uniqueness => true
*the relation model
class Relation < ActiveRecord::Base
belongs_to :follower, :class_name => "User"
belongs_to :following, :class_name => "User"
end
*relation controller
class RelationController < ApplicationController
def create
follow = User.find(params[:relation][:following_id])
#current_user.following << follow
redirect_to follow
end
*my ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include WelcomeHelper
before_filter :set_current_user
private
def set_current_user
#current_user = User.find(session[:user_id]) if session[:user_id]
end
end
*my action view
<h2><%= #user.username%><br /></h2>
<%= #user.pass%><br />
<% if #current_user && #current_user != #user %>
<% if #current_user.following.include?(#user) %>
<%= link_to "Unfollow",
relation_path(#current_user.relation_for(#user)),
:method => :delete %>
<% else %>
<%= form_for #relation do |f| %>
<%= f.hidden_field :following_id, :value => #user.id %>
<%= f.submit "Follow" %>
<% end %>
<% end %>
<% end %>
<br>
<ul>
<% #user.following.each do |u| %>
<li><%= link_to u.username, u %></li>
<% end %>
</ul>
Followed By
<ul>
<% #user.followers.each do |u| %>
<li><%= link_to u.username, u %></li>
<% end %>
</ul>
This is my action to insert following_id
def create
follow = User.find(params[:relation][:following_id])
#current_user.following << follow
redirect_to follow
end
and my following_id has been sent
{"utf8"=>"✓",
"authenticity_token"=>"DIY42kGR9fZ54Pub+CDMuNNaHZ0aFnzSiWrkOFRBsdE=",
"relation"=>{"following_id"=>"11"},
"commit"=>"Follow"}
I am trying to implement an employee recurrent deductions table through check boxes using simple_form. My code works but the selected recurrent deductions are not saved in my table. I can't work out why.
Here are my models.
class Employee < ActiveRecord::Base
belongs_to :club
has_many :employee_recurrents
has_many :recurrents, :through => :employee_recurrents
end
class Recurrent < ActiveRecord::Base
belongs_to :club
has_many :employee_recurrents
has_many :employees, :through => :employee_recurrents
end
class EmployeeRecurrent < ActiveRecord::Base
belongs_to :employee
belongs_to :recurrent
end
migration
class CreateEmployeeRecurrents < ActiveRecord::Migration
def change
create_table :employee_recurrents, :id => false do |t|
t.references :employee
t.references :recurrent
end
add_index :employee_recurrents, [:employee_id, :recurrent_id]
add_index :employee_recurrents, [:recurrent_id, :employee_id]
end
end
form
<%= simple_form_for #employee, html: {class: 'form-horizontal' } do |f| %>
<%= f.error_notification %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.association :recurrents,
as: :check_boxes,
label_method: :description,
value_method: :id,
label: 'Recurrent Deductions' %>
<%= f.button :submit, class: 'btn btn-primary' %>
<% end %>
controller
def employee_params
params.require(:employee).permit(:first_name, :recurrent_ids)
end
here is my edited log
Started PATCH "/employees/1" for 127.0.0.1 at 2013-08-12 19:38:42 +0800
Processing by EmployeesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"IwWzcT2qQJqHkTumWjb3OD5nJe9xLaA+YezMumer9X8=", "employee"=>{"job_id"=>"5", "manager_id"=>"", "first_name"=>"Mark", "recurrent_ids"=>["1", ""]}, "commit"=>"Update Employee", "id"=>"1"}
[1m[36mActiveRecord::SessionStore::Session Load (1.2ms)[0m [1mSELECT "sessions".* FROM "sessions" WHERE "sessions"."session_id" = '9a8b066a4033f8fa2ed867371ffaa2a3' ORDER BY "sessions"."id" ASC LIMIT 1[0m
[1m[35mUser Load (0.5ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
[1m[36mEmployee Load (0.8ms)[0m [1mSELECT "employees".* FROM "employees" WHERE "employees"."id" = $1 ORDER BY last_name, first_name LIMIT 1[0m [["id", "1"]]
Unpermitted parameters: recurrent_ids
[1m[35m (0.6ms)[0m BEGIN
[1m[36mEmployee Exists (1.1ms)[0m [1mSELECT 1 AS one FROM "employees" WHERE ("employees"."email" = 'mark#yahoo.com' AND "employees"."id" != 1 AND "employees"."club_id" = 1) LIMIT 1[0m
[1m[35m (0.4ms)[0m COMMIT
Redirected to http://localhost:3000/employees
Completed 302 Found in 22ms (ActiveRecord: 4.6ms)
I needed the following strong params
def employee_params
params.require(:employee).permit(:first_name, :recurrent_ids => [])
end
My problem is that a tag wont be created which is nested in posts.
I have Post which have tags nested in them. Like this
resources :posts do
resources :tags, :only => [:new, :create, :destroy]
end
In my tags controller i have this
class TagsController < ApplicationController
before_filter :authenticate_user!
def new
#post = Post.find(params[:post_id])
#tag = Tag.new
end
def create
#post = Post.find(params[:post_id])
#tag = #post.tags.build(params[:tags])
if #tag.save
flash[:notice] = "Tag created"
redirect_to #tag.post
else
flash[:error] = "Could not add tag at this time"
redirect_to #tag.post
end
end
end
new.html.erb
<%= form_for [#post, #tag] do |f| %>
<% if #tag.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#tag.errors.count, "error") %> prohibited this tag from being saved:</h2>
<ul>
<% #tag.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_field :tagable_type, :placeholder => "Type" %>
</div>
<div class="field">
<%= f.text_field :tagable_id, :placeholder => "Id" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Tag model
class Tag < ActiveRecord::Base
attr_accessible :post_id, :user_id, :tagable_type, :tagable_id
validates :post_id, presence: true
belongs_to :tagable, :polymorphic => true
belongs_to :post
belongs_to :user
end
Post model
class Post < ActiveRecord::Base
attr_accessible :body, :link, :thumbnail, :title, :user_id, :youtube, :youtube_id, :website_name, :image_field
default_scope order: 'posts.active DESC'
has_many :tags, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
belongs_to :user
end
UPDATE:
Now i can create a tag but the tagable_type and tagable_id fields are not being created for some reaseon
Started POST "/posts/18/tags" for 127.0.0.1 at 2013-06-26 15:54:14 +0200
Processing by TagsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gwpTs0Qqcrre4tH974RrfpaENGZKtSbkJx2U0H67AcM=", "tag"=>{"tagable_type"=>"Player", "tagable_id"=>"2"}, "commit"=>"Create Tag", "post_id"=>"18"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? ORDER BY posts.active DESC LIMIT 1 [["id", "18"]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "tags" ("created_at", "post_id", "tagable_id", "tagable_type", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Wed, 26 Jun 2013 13:54:14 UTC +00:00], ["post_id", 18], ["tagable_id", nil], ["tagable_type", nil], ["updated_at", Wed, 26 Jun 2013 13:54:14 UTC +00:00], ["user_id", 1]]
(6.9ms) commit transaction
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 18 ORDER BY posts.active DESC LIMIT 1
Redirected to http://localhost:3000/posts/18
Completed 302 Found in 15ms (ActiveRecord: 7.9ms)
There is a typo in the create() action of your TagsController:
#tag = #post.tags.build(params[:tags])
The hash used to create the tag should be params[:tag], not params[:tags].
Noob question, I'm sure, but I can't seem to find my mistake. SymptomSets are saving w/ the proper user_id, but the nested symptoms disappear. Note that the user model structure is identical to that in the Rails Tutorial (save that it has_many :symptom_sets)
Models:
class SymptomSet < ActiveRecord::Base
attr_accessible :symptoms, :symptoms_attributes
belongs_to :user
has_many :symptoms, :dependent => :destroy
accepts_nested_attributes_for :symptoms, allow_destroy: true
end
class Symptom < ActiveRecord::Base
attr_accessible :name, :duration, :symptom_set_id
belongs_to :symptom_set
end
Controller:
class SymptomSetsController < ApplicationController
before_filter :signed_in_user, only: [:create, :new]
def new
#symptom_set = SymptomSet.new
3.times do
symptom = #symptom_set.symptoms.build
end
end
def create
#symptom_set = current_user.symptom_sets.build(params[:symptom_sets])
if #symptom_set.save
flash[:success] = "Symptoms submitted!"
redirect_to root_url
else
render 'static_pages/home'
end
end
And the View:
<%= simple_form_for #symptom_set, :html => { :class => 'form-inline' } do |f| %>
<%= f.fields_for :symptoms do |builder| %>
<%= render 'symptom_fields', f: builder %>
<% end %>
<div class="actions"><%= f.submit %></div>
<% end %>
And the partial:
<%= f.input :name,
:collection=> ["Cough", "Fever", "Headache", "Lethargy"],
label: "Symptom",
prompt: "Select a symptom",
:input_html => { :class => "span3" }%>
<%= f.input :duration,
:collection => 1..14,
label: "Duration",
prompt: "How many days?" %>
finally, the rails server console outputs the following:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"s7ksuk40M2r76Nq4PGEEpTpkCECxFniP4TtpfSHszQk=", "symptom_set"=>{"symptoms_attributes"=>{"0"=>{"name"=>"Cough", "_destroy"=>"false", "duration"=>"2"}, "1
"=>{"name"=>"Fever", "_destroy"=>"false", "duration"=>"2"}, "2"=>{"name"=>"", "_destroy"=>"1", "duration"=>""}}}, "commit"=>"Create Symptom set"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" ='OH6_nuvySNjd6AbTuDunsw' LIMIT 1
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "symptom_sets" ("created_at", "updated_at", "user_id") VALUES ($1, $2, $3)
RETURNING "id" [["created_at", Tue, 05 Feb 2013 21:12:07 UTC +00:00], ["updated_at", Tue, 05 Feb 20
13 21:12:07 UTC +00:00], ["user_id", 1]]
(1.1ms) COMMIT
I'd try changing:
#symptom_set = current_user.symptom_sets.build(params[:symptom_sets])
to:
#symptom_set = current_user.symptom_sets.new(params[:symptom_sets])
I don't know if build would work there.
And also checking the params on the terminal log if it is called symptom_sets and if it's sending the parameters of nested form attributes.
EDIT:
I Really think your param's name would be symptom_set in singular. check that.