Has many to many checkboxes won't save Rails 4 - checkbox

I've tried making my has and belongs to many relation to work, following the Rails guides and everything I could find online, but they just wont show up.. When I save my form its only INSERTS into the Pin model, it doesn't insert any relations. If I add the relation manually via terminal like so:
p = Pin.new
p.minors = [1,2]
p.save
It works, but my form which looks like this (iam using rails 4, so collections yay) it doesn't save the relations (it saves the pin just fine)
new.html.erb
<%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %>
<%= collection_check_boxes(:competence_ids, :competence_ids, Competence.all, :id, :name) %>
pinscontroller.rb
class PinsController < ApplicationController
def create
#pin = Pin.new(pin_params)
#pin.user_id = current_user.id
if #pin.save
redirect_to pin_path(#pin)
end
end
def new
#pin = Pin.new()
end
def show
#pin = Pin.find(params[:id])
end
private
def pin_params
params.require(:pin).permit(:title, :name, :url, { :minor_ids => [] }, { :competence_ids => [] },)
end
end
and my model Pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :minors
has_and_belongs_to_many :competences
end
Minor.rb
class Minor < ActiveRecord::Base
has_and_belongs_to_many :pins
end
Competence.rb
class Competence < ActiveRecord::Base
has_and_belongs_to_many :pins
end
pin/show.html.erb
This is the way I try to check if the relations came through. They all come back empty and 0, except for the ones I did through console.
<%= #pin.minors.count.inspect %>
<%= #pin.competences.count.inspect %>
<% if !#pin.minors.empty? %>
<%= #pin.minors.each do |minor| %>
<%= minor.name %>
<% end %>
<% end %>
<% if !#pin.competences.empty? %>
<%= #pin.competences.each do |comp| %>
<%= comp.name %>
<% end %>
<% end %>
Schema.rb
create_table "competences", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "pin_id"
end
create_table "competences_pins", force: true do |t|
t.integer "pin_id"
t.integer "competence_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "minors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "pin_id"
end
create_table "minors_pins", force: true do |t|
t.integer "pin_id"
t.integer "minor_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pins", force: true do |t|
t.string "title"
t.string "url"
t.string "image"
t.string "username"
t.integer "views"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
So, am I missing a step? So far i've tried everything but the minors_pins and the competences_pins tables remain empty, all the help and insight I can get!

I fixed this by adding #minors = Minor.all in the pins controller in the new method. And by replacing <%= collection_check_boxes(:minor_ids, :minor_ids, Minor.all, :id, :name) %> with <%= f.collection_check_boxes(:minor_ids, #minors, :id,:name)%>

Related

Laravel Eloquent Collection Search always returns false

When I use the Laravel Collection search function it always returns false.
Code :
$entries = Entry::all();
$results = $entries->search('Jack', true);
dd($results);
Output :false
Output dd($entries) :
Collection {#218 ▼
#items: array:9 [▼
0 => Entry {#219 ▼
#fillable: array:2 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▶]
#original: array:5 [▶]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => Entry {#220 ▶}
2 => Entry {#221 ▶}
3 => Entry {#222 ▶}
4 => Entry {#223 ▶}
5 => Entry {#224 ▶}
6 => Entry {#225 ▶}
7 => Entry {#226 ▶}
8 => Entry {#227 ▶}
]
}
Sorry for the horrible formatting.
You need to use a simple collection with search() method. So, if you want to search for names, do this:
$entries = Entry::pluck('name');
$results = $entries->search('Jack');
BTW, this is a really bad way to do the search, because it will first load all entries into the memory and then will do the search.
A much better approach is to use Eloquent or Query Builder:
$results = Entry::where('name', 'like', '%'.$name.'%')->get();
Or simply:
$results = Entry::where('name', $name)->get();
When you want to search for a whole name.
You can always use the filter() function of Laravel Collections:
$matchingRecords = $allRecords->filter(function($key, $record){
return $record->name == "Jack";
});
Alternatives are the first() function to limit results to the first found, or search().
Check https://laravel.com/docs/5.4/collections#available-methods for more information.
Is there any value in your collection holding Jack ? and not f.e. 'jack' ?
According to the docs
https://laravel.com/docs/5.4/scout#searching
Entry::search('Jack')->get();
should do the trick, install the drivers tho.
I added the Eloquence[0] package.
[0] = https://github.com/jarektkaczyk/eloquence

Ruby key value pairs not printing correctly

I am trying to match key value pairs in an array and print them in a clear format:
array = [
{
'name' => 'Tom',
'age' => '31',
'weight' => '180'
},
{
'name' => 'Jane',
'age' => '24',
'weight' => '110'
}
]
array.each do |key, value|
if #{key} == "name"
puts "Name_is=#{key}"
else
puts "#{key}=#{value}"
end
end
This results in:
Name_is={"name"=>"Tom", "age"=>"31", "weight"=>"180"}
{"name"=>"Tom", "age"=>"31", "weight"=>"180"}=
Name_is={"name"=>"Jane", "age"=>"24", "weight"=>"110"}
{"name"=>"Jane", "age"=>"24", "weight"=>"110"}=
Expected result is:
Name_is=Tom
age=31
weight=180
Name_is=Jane
age=24
weight=110
What am I not doing right?
You have an array of hashes, you need to make a nested loop which loops over the array and, for each hash in the array, loops on the key/value pairs:
array.each do |hash|
hash.each do |key, value|
if key == "name"
puts "Name_is=#{key}"
else
puts "#{key}=#{value}"
end
end
end
Also I'm not sure why you have if #{key} == "name" while you can simply have if key == "name".
I think this is a Ruby-like solution:
array = [
{
'name' => 'Tom',
'age' => '31',
'weight' => '180'
},
{
'name' => 'Jane',
'age' => '24',
'weight' => '110'
}
]
array.each do |hash|
hash['Name_is'] = hash.delete 'name'
hash.each do |key, value|
puts "#{key}=#{value}"
end
end

Array in array not correctly interpreted by foreach loop in Puppet erb

$array_one = [
'one',
'two'
]
$variables = [
'world',
'a',
'b',
$array_one
]
file { '/tmp/test':
content => template("test/test.erb")
}
test.erb
<% #variables.each do |variable| %>
hello_<%= variable %>
<% end %>
results in:
hello_world
hello_a
hello_b
hello_onetwo
while it is an array according notify {$variables:}:
Notice: b
Notice: /Stage[main]/Test/Notify[b]/message: defined 'message' as 'b'
Notice: world
Notice: /Stage[main]/Test/Notify[world]/message: defined 'message' as 'world'
Notice: one
Notice: /Stage[main]/Test/Notify[one]/message: defined 'message' as 'one'
Notice: a
Notice: /Stage[main]/Test/Notify[a]/message: defined 'message' as 'a'
Notice: two
Notice: /Stage[main]/Test/Notify[two]/message: defined 'message' as 'two'
Notice: Finished catalog run in 0.17 seconds
Your Ruby loop does exactly what you ask of it. The notify resource implicitly flattens the array, apparently, so the erb equivalent would be
<% #variables.flatten.each do |variable| %>
hello_<%= variable %>
<% end %>

has_many :through query between 2 models

I've been searching for hours trying to find a up-to-date example of a mutual has_many :through between 2 models that actually worked, so I finally decided I'd just ask.
My database:
schema.rb
#...
create_table "groups", force: true do |t|
t.string "group_name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "memberships", force: true do |t|
t.integer "student_id"
t.integer "group_id"
end
create_table "students", force: true do |t|
t.string "user_name"
t.string "first_name"
t.string "last_name"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
#...
My models:
student.rb
class Student < ActiveRecord::Base
has_secure_password
validates :password, length: { in: 6..20 }
validates :user_name, format: {with:/\w{2,7}\.\d{1,4}/}, on: :create
validates_uniqueness_of :user_name, on: :create
validates_presence_of :first_name, on: :create
validates_presence_of :last_name, on: :create
has_many :memberships,  :dependent => :destroy
has_many :groups, through: :memberships
has_many :ratings,  :dependent => :destroy
end
group.rb
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :students, through: :memberships
validates_uniqueness_of :group_name
end
membership.rb
class Membership < ActiveRecord::Base
belongs_to :students
belongs_to :groups
end
If my authorization correctly puts the logged-in student's :user_name into session[:user_name] if I wanted to get all of the groups to which that student belonged, what would be the proper line(s)? I'm also interested in finding the students within a given group.
I tried:
#current_student = Student.find_by_user_name(session[:user_name])
#current_groups = #current_student.groups
But I was given:
uninitialized constant Student::Groups
What did I do wrong?
Change membership.rb to :
class Membership < ActiveRecord::Base
belongs_to :student
belongs_to :group
end

Rails 4.0.3 Active-Admin has_many checkboxes not saving

I using rails 4.0.3 and am trying to set up many to many checkboxes in Active-Admin. The checkbox selections are not being saved. This is what i have
class Product < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categorizations
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :products, :through => :categorizations
accepts_nested_attributes_for :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
ActiveAdmin.register Product do
permit_params :title, :price, category_ids:[:id]
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "Product" do
f.input :title
f.input :price
f.input :categories, :as => :check_boxes
end
f.actions
end
end
I have also tried using has_and_belongs_to_many but still cant not get the selections to save.
Any guidance would be highly appreciated.
Cheers
I found that adding the following to your active_admin file, product.rb, fixes it.
ActiveAdmin.register Product do
permit_params category_ids: []
end
try add
permit_params :title, :price, category_ids:[:id],
categories_attributes: [:id, :your_fields, :_update,:_create]

Resources