Dropdown depending on another collection_select rubyonrails - ruby-on-rails-4

Guys that is my code thing is I want to select a parent subject and upon selection I need to use that selected subject to list the topics within it in the parent field how can i do that?
<label>Parent Subject</label>
<div class="field">
<%= collection_select :topic, :subject_id, Subject.all, :id, :name %>
</div>
<label>Parent Topic</label>
<div class="field">
<%= collection_select :topic, :parent_id, ?????, :id, :name %>
</div>

Would this help? Rails dependent collection_select fields in form
If not, I am about to build something and might be happy to share it if it isn't to ugly!

Related

Simple form submit button not working

somehow my form is not working and I dont know why. Heres my code:
<%= simple_form_for #cr, url: edit_cr_path do |f| %>
<hr>
Design Office Involvements<br>
<%= f.collection_check_boxes :design_office_ids, DesignOffice.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
Procurement Involvements<br>
<%= f.collection_check_boxes :procurement_ids, Procurement.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
Installation Involvements<br>
<%= f.collection_check_boxes :installation_ids, Installation.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
<div class="row">
<div class="col-md-6">
Assessment Status
<%= f.input :assessment_status, :collection => [['Impacted','Impacted'],['Not impacted','Not impacted'],['Under assessment','Under assessment'],['New','New']], label: false, selected: ['New', 'New'] %>
</div>
<div class="col-md-6">
<div style="float: right">
<%= f.button :submit, 'Save' %>
</div>
</div>
</div>
<br>
<% end %>
Controller methods looking like this:
class CrsController < ApplicationController
def edit
#cr = Cr.find(params[:id])
end
def update
#cr = Cr.find(params[:id])
#cr.update_attributes(cr_params)
redirect_to edit_cr_path(#cr)
end
private
def cr_params
params.require(:user).permit(:id, :assessment_status)
end
end
And routes like this:
EndToEndManagement::Application.routes.draw do
get '/cr/:id', :to => 'crs#edit', :as => 'edit_cr'
put '/cr/:id', :to => 'crs#update'
patch '/cr/:id', :to => 'crs#update'
end
And thats the html code rails makes of my submit button:
<div class="col-md-6">
<div style="float: right">
<input class="btn" name="commit" type="submit" value="Save" />
</div>
</div>
I think the submit button is not correctly attached to the form but I tried to move it and clear some divs but nothing worked.
Best regards.
EDIT:
Thats what I tested
Removed my routes in routes.rb and replaced it with resources :crs and changed my first line in the form to <%= simple_form_for #cr do |f| %>. Didnt work!
Changed my simple_form to normal form. Didnt work!
Wrote a whole testapp with a scaffold and this form an it worked but I dont know why so I added part by part to my actual app and nothing made it working.
Found my mistake! Not that it would be so mind blowing but I will still post it :D
Had this small mistake in my application.html.erb
<div style="font-size: 1.3em"
<%= yield %>
</div>
Changed it to:
<div style="font-size: 1.3em">
<%= yield %>
</div>
And now it works fine.
It does not seem as edit_cr_path is the right url to go when you're trying to save a form.
You'll need another route:
post '/crs', :to => 'crs#create'
In your view, you probably won't need the url option as Rails can infer just looking at the object.
<%= simple_form_for #cr do |f| %>
But your object needs to be a new instance coming from your controller:
class CrsController < ApplicationController
def new
#cr = Cr.new #or whatever else to initialize the object
end
def create
#save the instance here
end

How do you use Active Record Enum Radio Buttons in a form?

In my app, there is a comment section on articles. I'd like the user to have the ability to comment with 3 different options. To activate this, I am using an Active Record Enum. Please note that the comment sections is nested under the articles.
resources :articles, only: [:index, :show] do
resources :comments
end
Migration:
class AddEnumToCommentModel < ActiveRecord::Migration
def change
add_column :comments, :post_as, :integer, default: 0
end
end
Comment model:
enum post_as: %w(username, oneliner, anonymous)
I attempted to add this to the content view, but lost. I am guessing I also have to do something in my controller but not sure.
Attempted view :
<%= form_for([#article, #comment]) do |f| %>
<% if #comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% #comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<h3>Fill in your comment</h3>
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="post_as">
<h3> Choose how you want to post your comment :</h3>
<%= f.input :content, post_as: ???, as: :radio %>
</div>
<br>
<div class="actions">
<%= f.submit %>
</div>
<br>
<% end %>
Rails creates a class method using the pluralized attribute name when you use enum. The method returns a key value pair of strings you've defined and what integers they map to. So, you could do something like this:
<% Comment.post_as.keys.each do |post_as| %>
<%= f.radio_button :post_as, post_as %>
<%= f.label post_as.to_sym %>
<% end %>
There's also collection_radio_buttons, which is more succinct than the other options.
<%= f.collection_radio_buttons :post_as, Comment.post_as, :second, :first %>
Those last two arguments specify how to get the input's value and label text. In your example Comment.post_as produces a hash of enum key names to the underlying integer, so we can grab those using :second for the integer and :first for the name — easy!
Here's what that produces:
<input type="radio" value="0" name="comment[post_as]" id="comment_post_as_0">
<label for="comment_post_as_0">username</label>
# Etc.
You can also customize the HTML by passing a block, which is my preferred way to create enum radio buttons with clickable labels:
<%= f.collection_radio_buttons :post_as, Comment.post_as, :second, :first do |b|
b.label { b.radio_button + b.text }
end %>
An addition to xxyyxx's answer, if you want the labels to be clickable as well:
<% Comment.post_as.keys.each do |post_as| %>
<%= f.radio_button :post_as, post_as %>
<%= f.label "#{:post_as}_#{post_as.parameterize.underscore}", post_as %>
<% end %>
In the view instead of
<%= f.input :content, post_as: ???, as: :radio %>
you could have
<%= f.radio_button(:post_as, "username") %>
<%= label(:post_as, "Username") %>
<%= f.radio_button(:post_as, "oneliner") %>
<%= label(:post_as, "Oneline") %>
<%= f.radio_button(:post_as, "anonymous") %>
<%= label(:post_as, "Anonymous") %>
Source: http://guides.rubyonrails.org/form_helpers.html#radio-buttons

Rails 4 - devise not displaying authentication errors

I'm in the process of building a rails 4 app and I've run into a snag. When I go to the sign in page and enter the information correctly everything works
If I go to sign in but I don't input one of the required fields (name, email, etc) it will put up an error message saying 'Please review the problems below:' but the specific error messages, such as 'email can't be blank' do not show up.
The errors displayed properly before I added styling..
The code is here:
https://github.com/mikejames386/Black-Fret
I'm currently working off the devise branch.
This is the first time I've ever asked a question on stackoverflow so please let me know if there is any other info needed.
<div class="container">
<div id="form_container"><!-- start form_container -->
<h1>New Artist</h1>
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<h2>Artist or Band Name</h2>
<div class="form_section">
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<br class="clear_both"/>
</div> <!-- end form_section -->
<h2>Primary Contact</h2>
<div class="form_section">
<div class="field">
<%= f.label :primary_first_name, 'First Name'%>
<%= f.text_field :primary_first_name %>
</div>
<div class="field">
<%= f.label :primary_last_name, 'Last Name'%>
<%= f.text_field :primary_last_name %>
</div>
<div class="field">
<%= f.label :email, 'Email'%>
<%= f.text_field :email %>
</div>
<br class="clear_both"/>
</div> <!-- end form_section -->
<h2>Password</h2>
<div class="form_section">
<div class="field"><%= f.label :password %>
<%= f.password_field :password %></div>
<div class="field"><%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</div>
<br class="clear_both"/>
</div>
<h2>Members</h2>
<div class="form_section">
<p>member multi-add goes here</p>
</div> <!-- end form_section -->
<%= f.submit "Add Artist", :class =>'btn btn-custom' %>
<% end %>
</div> <!-- end form_container -->
Errors on Devise log-in page are added as flash messages.
In order to capture them, add following lines in app/views/layouts/application.html.erb
<% flash.each do |name, msg| %>
<%= content_tag :div, msg %>
<% end %>
As per Devise Documentation
Remember that Devise uses flash messages to let users know if sign in
was successful or failed. Devise expects your application to call
flash[:notice] and flash[:alert] as appropriate. Do not print the
entire flash hash, print only specific keys. In some circumstances,
Devise adds a :timedout key to the flash hash, which is not meant for
display. Remove this key from the hash if you intend to print the
entire hash.
I have Devise set up on rails 4 with my app and I actually have a Devise User model, a registration controller (which youdon't need) and a Devise views section. You may want to follow this tutorial https://github.com/plataformatec/devise, if you scroll down a bit you will see configuring views. The below will get put into your user model and the validatable is for validations on email and password which may be why the validations are not working properly just a thought. But I hope this tutorial gives you some guidance.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
After you install Devise and add it to your Gemfile, you need to run the generator:
rails generate devise:install
After you install Devise and add it to your Gemfile, you need to run the generator:
The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it. When you are done, you are ready to add Devise to any of your models using the generator:
rails generate devise MODEL
Replace MODEL by the class name used for the applications users, it's frequently User but could also be Admin. This will create a model (if one does not exist) and configure it with default Devise modules. Next, you'll usually run rake db:migrate as the generator will have created a migration file (if your ORM supports them). This generator also configures your config/routes.rb file to point to the Devise controller.
Configuring views
We built Devise to help you quickly develop an application that uses authentication. However, we don't want to be in your way when you need to customize it.
Since Devise is an engine, all its views are packaged inside the gem. These views will help you get started, but after some time you may want to change them. If this is the case, you just need to invoke the following generator, and it will copy all views to your application:
rails generate devise:views

Conditioning based on checkbox status

When a potential User is editing their Profile, they have an option to show/hide some information from public view. I did that with
<div class="field">
<%= f.text_field :contact %>
<%= f.select(:contact_type_id, ContactType.all.map {|l| [l.name, l.id]}) %>
<%= f.check_box :visible %>
<%= f.label :visible, "Vidljivo" %>
<%= f.link_to_remove "Izbriši kontakt" %>
</div>
in a partial that's called in the view like this
<%= f.fields_for :contacts do |l| %>
<%= render 'contacts_form', f: l %>
<% end %>
What I now want is to display on a public profile page only that information that the User marked as visible, and I tried it through a different partial
<div class="field">
<% if :visible == true %>
<%= f.text_field :contact %>
<% end %>
</div>
called from
<%= f.fields_for :contacts do |l| %>
<%= render 'contacts_show', f: l %>
<% end %>
but it doesn't work. I tried tons of variations, but it all came down to guessing the right syntax. How do I display only those entries which visibility is marked as "true"?
Why are you displaying the public profile as a form? If you only want to show the information you can iterate over the contact information of the user where the contact type is visible.
I solved it by using a different approach. In my user controller I defined an instance variable #visible and passed it the array consisting of all database entries that have visible parameter set to true. Then I used #visible.each in the view to print the desired content.

Rails 4 use of non-model attributes in params resulting in undefined method `merge' for nil:NilClass

I have a search form on an index page for my Properties model which is using both Ransack and Geocoder to search the Properties model fields as well as narrow the results down based on distance from an address input by the user in the search form.
The address and distance are captured in the form with :nearaddress and :distance, respectively, which I send in params[:near]. I am checking for the presence of them in the controller index action following this answer. The result is “undefined method `merge' for nil:NilClass” when navigating to /properties, so the view will not render. How do I enable these non-model form parameters to be passed to the controller properly? I think this might be a strong parameters issue but I'm stuck on how to permit these attributes that aren't in the Properties model. The error highlights the "f.text_field :nearaddress" line.
index.html.erb:
...form fields that work when excluding the two that follow...
<div class ="field">
<%= f.label :nearaddress, "Address" %>
<%= f.text_field :nearaddress, params[:near] %>
</div>
<div class ="field">
<%= label_tag :distance %>
<%= text_field_tag :distance, params[:near] %> miles
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
properties_controller.rb:
def index
if params[:near].present? && (params[:near].to_i >0)
#search = Property.near(params[:near]).search(params[:q])
else
#search = Property.search(params[:q])
end
#properties = #search.result(:distinct => true).paginate(:page => params[:page])
...
end
I was able to resolve this problem by removing the "f." and adding "_tag" to the :nearaddress field as well as specifying the params in the controller index:
<%= label_tag :nearaddress, "Near Address" %>
<%= text_field_tag :nearaddress, params[:near] %>
<%= label_tag :distance, "Distance From Address (mi)" %>
<%= text_field_tag :distance, params[:near] %>
<div class="actions"><%= f.submit "Search" %>
<% end %>
if params[:distance].present? && (params[:distance].to_i >0) && params[:nearaddress].present?
#search = Property.near(params[:nearaddress],params[:distance]).search(params[:q])
else
#search = Property.search(params[:q])
end