I am working on rails 5 app. The issue I am facing is I am defining a drop down to select the user from another table in blogs form.The associations are as below.
blog.rb
has_many :blogs
def set_full_name
self.full_name = [first_name, last_name].join(' ')
end
user.rb
belongs_to :user
The problem is in this select form instead of displaying just the first_name in the drop-down list, I was to show the full_name of the user which I have defined in the user model. How can I do that?
<%= form.collection_select :user_id, User.all, :id, :first_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>
You're calling :first_name for the text property. Use :full_name
<%= form.collection_select :user_id, User.all, :id, :full_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>
Related
I am creating simple blog level application. below are my models.
class User < ActiveRecord::Base
attr_accessible :name,:posts_count,:posts_attributes , :comments_attributes
has_many :posts
has_many :comments
accepts_nested_attributes_for :posts , :reject_if => proc{|post| post['name'].blank?} , :allow_destroy => true
end
class Post < ActiveRecord::Base
attr_accessible :name, :user_id ,:comments_attributes
belongs_to :user
has_many :comments
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content, :post_id, :user_id
belongs_to :user
belongs_to :post
end
I am trying to create user,post and comment in one form by using accepts_nested_attributes_for feature of rails. Below is my controller and view code.
Controller-----------
class UsersController < ApplicationController
def new
#user = User.new
#post = #user.posts.build
#post.comments.build
end
def create
#user = User.new(params[:user])
#user.save
end
end
Form----------
<%= form_for #user do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :posts do |users_post| %>
<br>Post
<%= users_post.text_field :name %>
<%= users_post.fields_for :comments do |comment| %>
<%= comment.text_field :content %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
With the above code i am successfully able to create new user,post and comment but the problem is that i am not able to assign newly created user to newly created comment.when i checked the newly created comment into the database i got below result.I am getting user_id field value of "nil".
#<Comment id: 4, user_id: nil, post_id: 14, content: "c", created_at: "2014-05-30 09:51:53", updated_at: "2014-05-30 09:51:53">
So I just want to know how we can assign newly created comment to newly created user???
Thanks,
You will have to explicitly assign user_id for comments! You are nesting comments under posts, so comments would be having post_id assigned by default but though you are nesting comments under user form indirectly, there is no direct nesting of comments under user, so user_id remains blank in comments.
Try writing after create callback in Comment model to set user_id
In comment.rb
after_create{|comment|
comment.user_id = post.user_id
comment.save
}
Hope this helps :)
i have a form consists of the following models
Employee.rb
class Employee < ActiveRecord::Base
attr_accessible :employee_number, :joining_date, :first_name, :middle_name, :last_name,
:gender, :job_title, :employee_department_id, :qualification, :experience_detail,
:experience_year, :experience_month, :status_description, :date_of_birth, :marital_status,
:children_count, :father_name, :mother_name, :husband_name, :blood_group, :nationality_id,
:home_address_line1, :home_address_line2, :home_city, :home_state, :home_pin_code,
:office_address_line1, :office_address_line2, :office_city, :office_state, :office_pin_code,
:office_phone1, :office_phone2, :mobile_phone, :home_phone, :email, :fax, :user_id,
:reporting_manager_id, :employee_grade_id, :office_country_id,
:home_country_id, :employee_category, :employee_position_id
belongs_to :employee_department
has_many :counselor_supervisors
belongs_to :employee_position
def to_label
full_name = first_name + " " + last_name
end
end
EmployeeDepartment.rb
class EmployeeDepartment < ActiveRecord::Base
attr_accessible :code, :name
has_many :employees
has_many :employee_positions
has_many :counselor_supervisors
has_many :batch_leadership_supervisors
def to_label
name
end
end
CounselorSupervisor.rb
class CounselorSupervisor < ActiveRecord::Base
attr_accessible :employee_id, :employee_department_id, :employee_position_id
belongs_to :employee
belongs_to :employee_department
has_many :batch_counselor_supervisors
def to_label
employee.to_label
end
end
BatchCounselorSupervisor.rb
class BatchCounselorSupervisor < ActiveRecord::Base
attr_accessible :counselor_supervisor_id , :employee_department_id , :counselor_batch_id,
:batch_counselor_advisors_attributes
has_many :batch_counselor_advisors
belongs_to :counselor_supervisor
belongs_to :employee_department
belongs_to :counselor_batch
accepts_nested_attributes_for :batch_counselor_advisors
end
Employee_position.rb
class EmployeePosition < ActiveRecord::Base
attr_accessible :position_title, :employee_department_id
has_many :employees
belongs_to :employee_department
def to_label
position_title
end
end
batch_counselor_supervisors/new.html.erb (part of the form which related to my question)
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id , collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors %>
<% end %>
the dropdown list appears like this:
If I added an employee which belongs to the first department "Business Administration", the form will be displayed correctly like this:
Update: after adding label_method: :to_label, so my form became like this :
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id ,
collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors, label_method: :to_label %>
<% end %>
the employee name displayed correctly but still the department name not displayed correctly as the following image:
Is this SQLite3 issue ? and What can I do in order to solve this if it sqlite3 issue or not.
From what I see, you only have an issue with the labels not being displayed correctly. Could you try to explicitly set the method on your input:
label_method: :to_label
For more information have a look at https://github.com/plataformatec/simple_form and search for *label_method*
What are the actual relevant rows in your Employee table and your EmployeePosition table?
In your Employee table you happen to have these 2 columns;
employee_position_id
employee_position.
Since employee_position is also a table name, it's bad/reduntant model structure which might be confusing your include method of the query. It's possible that in your tables, the rows are fully filled out to complete the first query, but not for any of your other queries even though you think it is.
Newbie question here.
I have two models which are related to each other:
class Relationship < ActiveRecord::Base
...
attr_accessible :source_item_id, :target_item_id
belongs_to :target_item, :class_name => "Item"
belongs_to :source_item, :class_name => "Item"
belongs_to :user
...
end
and:
class Item < ActiveRecord::Base
...
attr_accessible :address
...
end
Now, within my form, I already know the source_item_id. I want to be able to enter an address into the form, and create both a target_item, and the associated Relationship.
<%= form_for #new_relationship do |f| %>
<% #new_relationship.source_item_id = #current_item.id %>
<%= f.hidden_field :source_item_id %>
<%= f.submit "New Relationship" %>
<% end %>
You generally do the relationship in the controller and let the form just collect the data. If you are asking how to have a form with two models, check out this post here. I hope I understood your question right !!!
I have three tables, applicants, users and ratings. The basic idea is that each applicant gets assigned a rating by any number of users. This part I have working without any problems. However, if a user goes to edit their rating (which includes a score), the form adds a second rating. I need to change things so that each user can only assign one rating for a given applicant.
class Applicant < ActiveRecord::Base
has_many :ratings
accepts_nested_attributes_for :ratings, :allow_destroy => true
class User < ActiveRecord::Base
has_many :ratings
The rating table just contains an applicant_id, a user_id and a score.
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :applicant
validates_uniqueness_of :applicant_id, :scope => :user_id
The rating validation makes sure that a second rating is not accepted, but I need to change the associations (or the form) so that a second score option never appears.
My applicant form:
<%= f.fields_for :ratings do |builder| %>
<%= builder.collection_select :score, Rating::SCORES, :to_s, :humanize %>
<%= builder.hidden_field :user_id, :value => current_user.id %>
<%= builder.hidden_field :applicant_id, :value => #applicant.id %>
<% end %>
How do I specify (in the applicant model, I'd guess, since that's the form I'm editing) that the applicant_id, user_id combo in the ratings table has to be unique?
I ended up getting things working by doing the following.
In my applicant controller, I changed the edit method to:
def edit
#applicant = Applicant.find(params[:id])
#my_rating = Rating.where(:applicant_id => params[:id]).where(:user_id => current_user.id)
if #my_rating.empty?
#my_rating = #applicant.ratings.build
end
end
Since I can't make a scope using the current_user, I figured it would work here. Then, in the form, I changed the nested attribute fields to:
<%= f.fields_for :ratings, #my_rating do |builder| %>
<%= builder.collection_select :score, Rating::SCORES, :to_s, :humanize %>
<% if builder.object.user_id.nil?%>
<%= builder.hidden_field :user_id, :value => current_user.id %>
<% end %>
<% end %>
The other important bit is the uniqueness validation in the ratings model above. That made sure that each user could have only one rating per applicant.
This seems to work fine for me, but if anyone has suggestions on how to improve this, I'd love to hear them.
Basically I have two models: User and Godfather. The godfather table has three columns:
user_id (FK --> User)
user_godfather_id (FK --> User)
description (text)
Inside each model class, I am adding the following associations:
class User < ActiveRecord::Base
has_many :godfathers # for user_id
has_many :other_godfathers, :foreign_key => "user_godfather_id", :class_name => "Godfather"
accepts_nested_attributes_for :godfathers
end
class Godfather < ActiveRecord::Base
belongs_to :user
belongs_to :user_godfather, :class_name => "User"
end
Now my question is about how to manage the edit form of this nested attribute relationships.
Here is how my form looks like at the moment (using the nested_form_for gem):
<%= nested_form_for #user do |f| %>
<%= f.fields_for :godfathers do |godfather_form| %>
# Here I have an ID text field but what I want instead is
# to provide a username for this godfather.
<%= godfather_form.label :user_godfather_id %>
<%= godfather_form.text_field :user_godfather_id %>
<%= godfather_form.label :description %>
<%= godfather_form.text_field :description %>
<%= godfather_form.link_to_remove "Remove this godfather" %>
<% end %>
<%= f.link_to_add "Add a godfather", :godfathers %> <br/><br/>
<%= f.submit "Update Godfathers" %>
So as I said in the comments, my goal is to be able to provide a username for the godfather instead of an id. That username is a column in the User table by the way.
Any idea about how I should go about it?
Thanks!
Just use different names for the relations
class User < ActiveRecord::Base
has_many :godfathers # for user_id
has_many :some_other_godfathers, :foreign_key => "user_godfather_id", :class_name => "Godfather"
accepts_nested_attributes_for :godfathers
end
Now you can use godfathers and some_other_godfathers.
Hope that helps :-)