How do I capture select value from dropdown menu in rails? - ruby-on-rails-5

I have cities table and profiles table. Below is the models of both:
class City < ActiveRecord::Base
belongs_to :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
has_one :city
end
I am trying to create a dropdown list for cities in profile view page.
<%= form_for #profile, url: user_profile_path, :html => { :multipart => true} do |f| %>
<div class="field">
<%= f.label :country %>
<%= f.text_field :country %>
</div>
<div class="field">
<%= f.label :city_id %>
<%= f.select :city_id, options_for_select(#city.collect{ |u| [u.name, u.id] }) %>
</div>
<div class="actions">
<%= f.submit "Update Profile" %>
</div>
<% end %>
Here is the ProfilesController:
class ProfilesController < ApplicationController
def new
#user = User.find( params[:user_id] )
#profile = Profile.new
#city = City.all
end
def create
#user = User.find( params[:user_id] )
#profile = #user.build_profile(profile_params)
if #profile.save
flash[:success] = "Profile Updated!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
end
How do I add city_id column in the profiles table, I am unable to capture city_id from the above ProfilesController.
I tried to #city = City.find( params[:city_id] ) in "ProfilesController",
"Def create", and I got this error:
Couldn't find City with 'id'=
Please advice.

Maybe try to replace
has_one :city
by
belongs_to :city
in your profile model and in your city model replace
belongs_to :profile
by
has_many :profiles

try whitelisting city_id instead of city
private def profile_params
params.require(:profile).permit(:country, :city)
end
Change you associations-
class City < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :city
end
city_id column should be in that model where you are using belongs_to association

Related

unknown attribute X, but X is not in argument of update_attributes in rails3

I am trying to set object's field in the form with accept_nested_attributes. However in the controller when I do :
#device.update_attributes(params[:device])
I get :
ActiveRecord::UnknownAttributeError
"unknown attribute: device_id"
but device_id, which is an attribute of other non-related model, is not included in params.
Params are like following.
{"utf8"=>"✓",
"authenticity_token"=>"Xja5GCNRutpZn2c4wKeSx0KO6sNEzh09kWmPQ0/0Hys=",
"id"=>"5",
"device"=>{"routes_attributes"=>{"0"=>{"name"=>"",
"origin_attributes"=>{"name"=>"",
"lat"=>"",
"lng"=>""},
"destination_attributes"=>{"name"=>"",
"lat"=>"",
"lng"=>""}}}},
"commit"=>"Create Device"}
What can be thought as a cause.
Here are my codes.
view
<%= form_for #device, :url => {:action => "do_compose"}, :method => :post do |f| %>
<div class="field">
<%= select_tag(:id, options_for_select( Device.all.collect{|d| [d.name + "/" + d.get_driver().name, d.id] } ),:prompt=>"select a device") %>
</div>
<div class="field">
<%= render partial:"routes/nested_routes_form", locals: {route_object:#device.get_route(), parent_form:f} %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
controller
def do_compose
#device = Device.find(params[:id])
respond_to do |format|
if #device.update_attributes(params[:device])
format.html { redirect_to #device, notice: 'Device was successfully updated.' }
else
format.html { render action: comopse }
end
end
end
model
class Route < ActiveRecord::Base
attr_accessible :name, :destination_attributes, :origin_attributes, :waypoints, :driver_id
has_many :waypoints
has_one :origin, :class_name=>"Origin"
has_one :destination, :class_name=>"Destination"
belongs_to :device
accepts_nested_attributes_for :origin, :destination, :waypoints
end
class Device < ActiveRecord::Base
attr_accessible :id, :name, :password
attr_accessible :device_driver_bind_attributes, :drivers_attributes, :routes_attributes, :current_location_attributes
has_many :drivers, through: :device_driver_bind
has_many :device_driver_bind, dependent: :destroy
has_one :current_location, :class_name => "CurrentLocation"
has_many :routes
has_many :origins, through: :routes
has_many :destinations, through: :routes
has_many :waypoints, through: :routes
accepts_nested_attributes_for :routes, :current_location, :device_driver_bind
end
This has to be the problem in your select_tag, try this:
<%= f.select(:id, options_for_select( Device.all.collect{|d| [d.name + "/" + d.get_driver().name, d.id] } ),:prompt=>"select a device") %>
ActiveRecord::UnknownAttributeError
"unknown attribute: device_id"
looks like it's due to a missing column on Routes.
ActiveRecord expects to be able to set this with accepts_nested_attributes_for :routes, to satisfy belongs_to :device.

Rails - Nested Model Fails to Save

I'm rather new to Rails and I'm writing a signup form that includes nested models. When I submit the form, the user is saved just fine, but the nested model does not save anything to the Subscription db, and the console throws no errors.
I sincerely hope I'm not missing something insanely obvious, and I appreciate any tips you can share. Thanks!
Here is the code-
Models:
class Plan < ActiveRecord::Base
attr_accessible :posts, :name, :price
has_many :users
end
class User < ActiveRecord::Base
belongs_to :plan
has_many :events
has_one :subscription, :autosave => true
accepts_nested_attributes_for :subscription
attr_accessible :subscription_attributes
def save_with_payment
if valid?
customer = Stripe::Customer.create(
email:email,
plan: plan_id,
card: stripe_card_token )
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
end
class Subscription < ActiveRecord::Base
attr_accessible :plan_id, :status, :user_id
belongs_to :user
end
This is the User controller:
def new
#user = User.new
plan = Plan.find(params[:plan_id])
#user = plan.user
#user.build_subscription
end
def create
#user = User.new(params[:user])
if #user.save_with_payment
sign_in #user
flash[:success] = "Welcome to the SendEvent!"
redirect_to #user
else
render 'new'
end
end
This is the form:
<%= form_for #user, :html => {:class => "form-inline"} do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="control-group">
<%= f.label :name, :class => "control-label" %>
<%= f.text_field :name %>
</div>
# A few more fields here and...
# The nested model:
<%= f.fields_for :subscription do |builder| %>
<%= builder.hidden_field :status, :value => true %>
<% end %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary", id: "submitacct" %>
<% end %>
Sample app from RailsCasts
RailsCasts Episode #196: Nested Model Form (revised)
Maybe help you.

creating a join action between user and group correctly

I have a problem when trying to create a membership for users based on the name they input into the membership form - new.html.erb.
user.rb
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
membership.rb
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
group.rb
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
membership controller
def create
#group = Group.find_by_name(:group)
#membership = current_user.memberships.build(:group_id => #group.group_id)
if #membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end
membership - _form.html.erb
<%= form_for(#membership) do |f| %>
...
#error validation
...
<div class="field">
<%= f.label :group %><br />
<%= f.text_field :group %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What I want it to do is find the group inputted if it exists, and create the table entry in the memberships table accordingly. Just not sure if what I'm doing is on the right track. Any suggestions?
The reason your code isn't working now is because of this line:
#group = Group.find_by_name(:group)
it should be something like (I don't remember exactly sorry)
#group = Group.find_by_name(params[:membership][:group])
The error is getting called on the next line because #group is nil.
But you should probably handle that type of logic in the model anyway with a virtual attribute or something.
membership.rb
def group_name
if self.group
#group_name ||= self.group.name
end
end
def group_name=(group_name)
#group_name = group_name
self.group = Group.find_by_name(#group_name)
end
form
<div class="field">
<%= f.label :group_name, "Group" %><br />
<%= f.text_field :group_name %>
</div>
controller
def create
#membership = current_user.memberships.build(params[:membership])
if #membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end

saving record to join table Has_many :through

I am new to Rails 3 and having trouble with saving records in the Join table. I have been looking around and trying different examples found on this website and from the documentation or books, but I don't understand why I can't get it to work. I am trying to create Authorization by creating Roles and associate them to users. So far I have been trying to assign roles from the update action in the Users controller without prevail.
I have 3 models: the User.rb, role.rb, and assignment.rb (the join table)
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments, :foreign_key => :role_id
accepts_nested_attributes_for :roles
attr_accessor :password, :role_ids
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :status, :description, :username, :roles_attributes
...
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments, :foreign_key => :user_id
accepts_nested_attributes_for :users
attr_accessible :name
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :roles
end
The Users controller in the update action I have the following
class UsersController < ApplicationController
...
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
#user.roles.build
flash[:success] = "Profile updated"
redirect_to #user
else
#title = "Edit" + " " + #user.username
render 'edit'
end
end
...
end
and in the 'edit' view page I intend to have checkboxes to update the User record with an associated role:
EDIT: Changed the "check_box" with "check_box_tag" ... the check boxes appear properly, but the values are not saved.
<%= form_for(#user) do |f| %>
...
<div class="field">
<%= f.label :roles %><br />
<%= f.fields_for :role_ids do |r| %>
<% #roles.each do |role| %>
<%= check_box_tag "user[roles][]", role.id, #user.roles.include?(role.id) %>
<%= role.name %>
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
<% end %>
</div>
<% end %>
With this code I even get an error where 'Roles' have no association.
EDIT: this was corrected with the accepts_nested_attributes_for :role. Thanks!
No association found for name `roles'. Has it been defined yet?
I am really confused where I am doing something wrong. Your help would be much appreciated.
Aurelien
You have to use the same name with "accepts_nested_attributes_for" as you used defining the association:
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :role
end
Finally solved the problems and thought I could share.
The models associations but I did change the attr_accessible:
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments, :foreign_key => :role_id
accepts_nested_attributes_for :roles
attr_accessor :password
attr_accessible ..., :roles_ids
...
end
In the User controller for the edit and update action.
def edit
#title = "Edit" + " " + #user.username
#roles = Role.find(:all)
#user.assignments.build
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
redirect_to #user
else
#title = "Edit" + " " + #user.username
render 'edit'
end
end
The important part was the view part and assigning the right names for the checkbox tags
<%= form_for(#user) do |f| %>
<div class="field">
<%= f.label :roles %><br />
<%= f.fields_for :role_ids do |r| %>
<% #roles.each do |role| %>
<%= check_box_tag "user[role_ids][]", role.id, #user.roles.include?(role) %>
<%= role.name %>
<% end %>
<%= hidden_field_tag "user[role_ids][]", #user.id %>
<% end %>
</div>
The check_box_tag lets the form save an array and gives more control than check_box
Then in order to assign the multiple Role ids, the name of the check_box_tag should include user[roles_ids][].
Finally the last parameter of the check_box_tag returns if the User has already the roles and checks the checkboxes if true.
I must admit that the name part of the check_box_tags is really confusing but it works :).

Rails association - difficulty getting form_for to work

I have a Member model that belongs to User
class Member < ActiveRecord::Base
attr_accessible :name
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :members, :dependent => :destroy
end
In my Members controller I have
class MembersController < ApplicationController
def create
#user = User.find(params[:user_id])
#member = #user.members.build(params[:member])
if #member.save
flash[:success] = "Member created!"
redirect_to root_path
else
render 'pages/home'
end
end
end
In /app/views/users/show.html.erb I have
<%= form_for #member do |f| %>
<div class="field">
<%= f.text_area :name %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
But I get the following error:
undefined method `model_name' for NilClass:Class
Extracted source (around line #18):
15:
16: <h1 class="member">What's up?</h1>
17:
18: <%= form_for #member do |f| %>
My show action in the Users controller is
def show
#user = User.find(params[:id])
#members = Member.new
#title = #user.name
end
Which also contains the 'new' method
I have tried changing :user_id to :id in the MembersController but this does not work either. What am I doing wrong here?
thanks in advance
Try to replace #members = Member.new by #member = Member.new ;-) !
I needed to pass the #user.id as a hidden field in the form, for the association to work!