Attributes not showing on users#show page - ruby-on-rails

users_controller.rb
class ProfilesController < ApplicationController
before_filter :authenticate_user!
def show
#user = User.find(params[:id]) || User.find(current_user.id)
#questions_for_about = #user.questions.for_about.order('id asc')
#questions_for_personality = #user.questions.for_personality.order('id asc')
end
end
user#show.html.erb
<div class="element">
Ethinicity:
<%= #user.ethnicity.present? ? #user.ethnicity.name : "" %>
</div>
<div class="element">
Education:
<span class="select_for_education">
<%= #user.education.present? ? #user.education.name : "" %>
</div>
The user.education.name is just showing the following - Education:
Without showing the users Education in which was chosen on his personal profile using the following select:
<div class="element">
Ethinicity:
<%= best_in_place current_user, :ethnicity_id, :type => :select, collection: Ethnicity.all.map{|e| [e.id, e.name]}, :inner_class => 'education-edit', nil: 'Select Ethnicity' %>
</div>
<div class="element">
Education:
<span class="select_for_education">
<%= best_in_place current_user, :education_id, :type => :select, collection: Education.all.map{|e| [e.id, e.name]}, :inner_class => 'education-edit', nil: 'Select Education' %>
</div>
What am I doing wrong? And how can I get the users education that DOES display on his/her own profile to display in the show page?
Thanks in advanced!
User.rb
class User < ActiveRecord::Base
include PgSearch
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable,
:omniauth_providers => [:facebook, :twitter, :linkedin]
attr_accessible :email, :password, :password_confirmation, :zip, :gender, :remember_me, :first_name, :last_name,
:birthday, :current_password, :occupation, :address, :interests, :aboutme, :profile_image,
:photos_attributes, :age, :education_id, :ethnicity_id, :blurb
has_many :authorizations, :dependent => :destroy
has_many :comments
has_many :events
has_many :photos, as: :attachable
has_many :questions
has_many :sent_messages, class_name: 'Message', foreign_key: :sender_id
has_many :received_messages, class_name: 'Message', foreign_key: :receiver_id
has_one :ethnicity
has_one :education
end
ethnicity.rb
class Ethinicity < ActiveRecord::Base
attr_accessible :name
has_many :users
end
education.rb
class Education < ActiveRecord::Base
attr_accessible :name
has_many :users
end

You're missing belongs_to association for has_many and has_one relation. The belongs_to association definition needs to be defined in the model whose table has the foreign key.
Given your models, although the other way around is imaginable, here is what I think the associations should look like:
# User Model
class User < ActiveRecord::Base
...
belongs_to :ethnicity
belongs_to :education
end
# Ethnicity Model
class Ethinicity < ActiveRecord::Base
attr_accessible :name
has_many :users
end
# Education Model
class Education < ActiveRecord::Base
attr_accessible :name
has_many :users
end

Related

Usage of f.collection_select in a has_many :through relation

Let me explain my problem,
what I'm trying to do is displaying a dropdown list of teams (one of my models) of which the current user is a member, to allow him to select which of his teams he would like to join a tournament (another model). Here's what I was thinking of doing (and failed doing so):
in the show view of a selected tournament
<%= form_for #new_team, :url => join_tournament_path do |f| %>
<%= f.collection_select :team_id, current_user.user_teams, team ids of user teams?, user teams names parameter i guess, include_blank: true %>
<%= f.submit %>
<% end %>
show action in the controller
def show
#tournament = Tournament.find(params[:id])
#new_team = #tournament.teams_in_tournaments.build
end
I'd like the form to send the the tournaments id along with the team id of the team selected by the user to my custom "join" controller action which would save the whole thing.
Hopefully someone could point me in a direction of a solution, because I think I don't really understand how the f.collection_select works (and the documentation wasn't really helpful in my case)
(excuse my english by the way)
EDIT:
My models and relationships:
Team:
class Team < ActiveRecord::Base
has_many :user_teams
has_many :users, :through => :user_teams
has_many :teams_in_tournaments
has_many :tournaments, :through => :teams_in_tournaments
belongs_to :team_leader, class_name: "User"
end
User:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :user_teams
has_many :teams, :through => :user_teams
end
Tournament:
class Tournament < ActiveRecord::Base
has_many :teams_in_tournaments
has_many :teams, :through => :teams_in_tournaments
belongs_to :organizer, class_name: "User"
end
UserTeam:
class UserTeam < ActiveRecord::Base
belongs_to :user
belongs_to :team
validates :team_id, :uniqueness => { :scope => :user_id }
end
TeamsInTournament:
class TeamsInTournament < ActiveRecord::Base
belongs_to :tournament
belongs_to :team
validates :team_id, :uniqueness => { :scope => :tournament_id }
end
You are halfway there, the only missing thing is to add id's and names of the objects you want outputted in the <option> elements
In your case it would be something like this:
<%= form_for #new_team, :url => join_tournament_path do |f| %>
<%= f.collection_select :team_id, current_user.user_teams, :id, :name, include_blank: true %>
<%= f.submit %>
<% end %>

Rails: Use a collection of checkboxes to add/remove entries on a different table with ActiveRecord

I have three objects: Contact, Sector, and Contact_sector.
Contact contains an id and some other irrelevant (non-reference) columns
Sector contains an id and sector column with ~10 editable entries
Contact_sector has a contact_id reference and a sector_id reference. In my mind I imagine that every sector that applies to some contact can be found here, and if a sector is un-applied it is removed from here.
I want to have a collection of checkboxes in the contact _form formed from list of entries in :sectors, but updating the form with certain boxes ticked adds/removes entries from :contact_sectors.
Where am I going wrong?
UPDATED: Fixed strong_params to permit sectors, now I am unable to find the sectors by id ActiveRecord::RecordNotFound (Couldn't find Sector with ID=["1", ""] for Contact with ID=1)
Models:
class Contact < ActiveRecord::Base
has_many :contact_sectors
has_many :sectors, through: :contact_sectors
accepts_nested_attributes_for :contact_sectors, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :sectors, :reject_if => :all_blank, :allow_destroy => true
end
class Sector < ActiveRecord::Base
has_many :contact_sectors
has_many :contacts, through: :contact_sectors
def name_with_initial
"#{sector}"
end
end
class ContactSector < ActiveRecord::Base
belongs_to :contact
belongs_to :sector
end
View:
<%= f.fields_for(:sectors) do |s| %>
<%= s.collection_check_boxes :id, Sector.all,
:id, :name_with_initial,
{ prompt: true }, { class: 'form-control' } %>
<% end %>
Controller
def edit
#contact.sectors.build
end
def contact_params
#Not sure if I need something like this or not
params['contact']['sectors'] = params['contact']['sectors']['id'].split(',')
params.require(:contact).permit(:firstname, :lastname,
contact_sectors_attributes: [:id],
sectors_attributes: [:_destroy, {:id => []}])
end
Instead of creating the join model explicitly you can just declare the relationship as has_many through: and let ActiveRecord handle the join model:
class Contact < ActiveRecord::Base
has_many :contact_sectors
has_many :sectors, through: :contact_sectors
accepts_nested_attributes_for :sector,
reject_if: :all_blank, allow_destroy: true
end
class Sector < ActiveRecord::Base
has_many :contact_sectors
has_many :contacts, through: :contact_sectors
end
class ContactSector < ActiveRecord::Base
belongs_to :contact
belongs_to :sector
end
<%= form_for(#contact) do |f| %>
<%= f.fields_for(:sectors) do |s| %>
<%= s.collection_check_boxes :id, Sector.all,
:id, :name_with_initial,
{ prompt: true }, { class: 'form-control' } %>
<% end %>
<% end %>
models
class Contact < ActiveRecord::Base
has_many :sectors, through: :contact_sectors
has_many :contact_sectors
accepts_nested_attributes_for :sectors
end
class Sector < ActiveRecord::Base
has_many :contacts, :through => :contact_sectors
has_many :contact_sectors
end
class ContactSector < ActiveRecord::Base
belongs_to :contact
belongs_to :sector
end
view
<%= form_for(#contact) do |f| %>
<% Sector.all.each do |sector| %>
<%= check_box_tag "contact[sector_ids][]", sector.id, f.object.sectors.include?(sector) %>
<%= sector.sector %>
<% end %>
<% end %>
controller
def update
#To make sure it updates when no boxes are ticked
#contact.attributes = {'sector_ids' => []}.merge(params[:contact] || {})
end
def contact_params
params.require(:contact).permit(:firstname, :lastname, sector_ids: [])
end
Recommended reading:
http://millarian.com/rails/quick-tip-has_many-through-checkboxes/
Rails 4 Form: has_many through: checkboxes

accepts_nested_attributes_for with belongs_to polymorphic devise

I have 3 models and this associations for them
class User < ActiveRecord::Base
# devise modules here
attr_accessible :email, :password, :password_confirmation, :remember_me, :rolable_id, :rolable_type
belongs_to :rolable, :polymorphic => true
end
class Player < ActiveRecord::Base
attr_accessible :age, :name, :position
has_one :user, :as => :rolable
end
class Manager < ActiveRecord::Base
attr_accessible :age, :name
has_one :user, :as => :rolable
end
I'm out of the box from rails way to put accepts_nested_attributes_for :rolable on user model and In this accepts_nested_attributes_for with belongs_to polymorphic question I found some solutions for it but all solution not works for me. All solutions, always the same error when I try to create a user
Processing by RegistrationsController#create as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"WKCniJza+PS5umMWCqvxFCZaRVQMPZBT4nU2fl994cU=", "user"=>{"email"=>"john#email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "rolable_type"=>"manager", "rolable"=>{"name"=>"john", "age"=>"24"}}, "commit"=>"Sign up"}
Completed 500 Internal Server Error in 143.0ms
NoMethodError (undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class):
app/controllers/registrations_controller.rb:13:in `new'
app/controllers/registrations_controller.rb:13:in `create'
My mistake, I'm use nested form
<%= f.fields_for :rolable do |rf| %>
....
<% end %>
change to
<%= f.fields_for :rolable_attributes do |rf| %>
....
<% end %>
for polymorphic association you have to maintain generic model Roll like
class User < ActiveRecord::Base
# devise modules here
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :rolls, :as => :rolable
end
class Player < ActiveRecord::Base
attr_accessible :age, :name, :position
has_many :rolls, :as => :rolable
end
class Manager < ActiveRecord::Base
attr_accessible :age, :name
has_many :rolls, :as => :rolable
end
class Roll < ActiveRecord::Base
attr_accessible :rolable_id, :rolable_type
belongs_to :rolable, :polymorphic=> true
end

Rails 3 has_many :through Form

Can't figure out why this is not working. First time using :has_many => :through
Keep getting uninitialized constant User::Employmentship
class User < ActiveRecord::Base
has_many :employmentships
has_many :companies, :through => :employmentships
accepts_nested_attributes_for :employmentships, :allow_destroy => true, :reject_if => proc { |obj| obj.blank? }
attr_accessible :email, :password, :password_confirmation, :firstname, :lastname, :username, :role, :company_ids
end
class Company < ActiveRecord::Base
has_many :employmentships
has_many :users, :through => :employmentships
end
/views/users/_form.html.erb
<p>
<%= for company in Company.all do %>
<%= check_box_tag "user[company_ids][]", company.id, #user.companies.include?(company) %>
<%= company.name%>
<% end %>
</p>
EDIT - If I change #user.companies.include?(company) to false i get the form, but nothing updates.
EDIT 2 -
class Employmentship < ActiveRecord::Base
belongs_to :company
belongs_to :user
attr_accessor :company_id, :user_id
end
Where is you employmentship model? has_many_through is for going through another model.

Rails 3 - Devise nested form giving mass assignment error

I know this has been covered a few time on here but I cant seem to solve this error -
WARNING: Can't mass-assign protected attributes: new_order_attributes
This is the nested hash that is trying to be saved -
Parameters: {"utf8"=>"✓","authenticity_token"=>"UNKZf7zvlyReHSCbMRRl+9y+F5/2YF8Rf64Wm9O9xyo=", "user"=>{ "new_orders_attributes"=>[{"plan_id"=>"2", "price_id"=>"2222"}], "first_name"=>"Alex", "last_name"=>"Handley", "email"=>"alex#s.co.uk", "job_title"=>"Programmer", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
The user data is saved but the order is not saved.
Models
User
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :location, :country, :job_title, :company, :parent_id,:first_name,:last_name,:subscription_type,
:orders, :plan_id, :user_id, :price_id
has_many :orders
has_many :plans, :through => :orders
accepts_nested_attributes_for :orders, :plans
Orders
class Order < ActiveRecord::Base
belongs_to :plan
belongs_to :user
end
Plans
has_many :orders
has_many :users, :through => :orders
Rails -v - 3.0.3
Nested Form
<% prefix = "user[new_orders_attributes][]" %>
<%= fields_for prefix, #user.orders do |order_form| %>
<%= order_form.hidden_field :plan_id, :value => 2 %>
<%= order_form.hidden_field :price_id, :value => 2222 %>
<% end %>
Thanks, Alex
Try adding orders_attributes to the attribute list in the attr_accessible statement.

Resources