Ruby on Rails 3 Select Helper Question - forms

Have have this line of code in my form when I create a new item. Though when I edit the item, the default selection isn't the one that is selected. Do I need to set the initial value?
<%= f.select :category, options_for_select(Item::CATEGORIES) %>

options_for_select accepts second param which identifies the selected value.
try
<%= f.collection_select :category_id, Item::CATEGORIES, :downcase, :titleize %>
It assumes your Item::CATEGORIES gives a array of strings of categories.
for each category in Item::CATEGORIES, category.downcase will be used as the option's value, while category.titleize will be used as the option's text.
ie.
<option value="<%= cate.downcase %>"><%= cate.titleize %></option>
======
or you could:
<%= f.select :category, options_for_select(Item::CATEGORIES, #cur_obj.category.id) %>

Related

Using inputs_for with #conn

I am attempting to create a form like this:
<%= form_for #form_object, registration_path(#conn, :register), [class: "register_form"], fn f -> %>
<div class="register_alert">
<%= Web.PartialView.render("flash_alert.html", conn: #conn) %>
<%= inputs_for f, :user, [default: %{name_first: nil}], fn fu -> %>
<%= label fu, :name_first, "FIRST NAME", class: "register_label" %>
<%= text_input fu, :name_first, class: "register_text-field"%>
<% end %>
<%= submit "Sign Up", class: "register_register-button" %>
</div>
<%end%>
That #form_object is a the conn passed in at first because I have no changeset until they enter data (create form). However, I keep getting the oh so helpful 'argument error' crash when trying to run this. If I remove the inputs_for section, everything is fine. How do you use inputs_for with a connection object in phoenix?
Phoenix 1.4.0 being used.
Plug.Conn is a struct containing nearly everything about the connection.
Phoenix.HTML.Form.form_for accepts the connection object as a first argument.
Since you were even of less help than Phoenix providing exactly zero information about the error message, I’d suggest the issue is in a well-formedness of #form_object. You clearly have #conn object there on hand, pass it as the first argument:
<%= form_for #conn, registration_path(#conn, :register) ...

Rails, choosing option in drop-down filters values in second drop-down

I'm trying to create some pages in my rails app, using bits and pieces of what I've learned from some Railscasts. My environment is as follows:
Rails 3.2.13
ruby 1.9.3p448
Using the chosen gem
Database SQLite
When I want to create a new profile, I would visit localhost:3000/profiles/new.
There I have a text box for my profile called Name. Next I have a drop-down
where the use can choose what profile type - Admin, Editor or User. Once an
option is selected, another drop-down becomes visible - Traits. The user can
then choose 1 or many traits.
For each profile type (Admin, Editor, User) there are different traits. So the
Traits model has fields name and trait_type where trait_type would have a value
of either Admin, Editor or User.
I'm having trouble coding the view, assuming I should code there, but maybe I
should be in a controller, getting the Traits drop-down to display only say
Admin traits if I choose a profile type of Admin.
Can someone please give me a nudge in a positive direction? Please keep in mind
that I'm new to this. Hope I am providing enough, and not too much information.
Note: The console.log entries in my profiles.js.coffee file is temporary, just
so I can see what is going on.
Thanks,
HoGi
-------------------------------------------------
/app/assets/javascripts/application.js
-------------------------------------------------
//= require jquery
//= require jquery_ujs
//= require chosen-jquery
//= require_tree .
-------------------------------------------------
-------------------------------------------------
/app/assets/javascripts/profiles.js.coffee
-------------------------------------------------
jQuery ->
$('#profile_trait_ids').chosen()
jQuery ->
$('#profile_trait_ids').parent().hide()
prof_types = $('#profile_prof_type').html()
console.log(prof_types)
$('#profile_prof_type').change ->
prof_type = $('#profile_prof_type :selected').text()
console.log(prof_type)
$('#profile_trait_ids').parent().show()
-------------------------------------------------
-------------------------------------------------
/app/assets/stylesheets/application.css
-------------------------------------------------
*= require_self
*= require chosen
*= require_tree .
*/
-------------------------------------------------
-------------------------------------------------
/app/models/profile.rb
-------------------------------------------------
class Profile < ActiveRecord::Base
attr_accessible :active, :name, :prof_type, :trait_ids
has_many :traitships
has_many :traits, through: :traitships
PROFILE_TYPES = ["Admin", "Editor", "User"]
end
-------------------------------------------------
-------------------------------------------------
/app/models/trait.rb
-------------------------------------------------
class Trait < ActiveRecord::Base
attr_accessible :active, :name, :trait_type
has_many :traitships
has_many :profiles, through: :traitships
end
-------------------------------------------------
-------------------------------------------------
/app/models/traitship
-------------------------------------------------
class Traitship < ActiveRecord::Base
#attr_accessible :profile_id, :traid_id
belongs_to :profile
belongs_to :trait
end
-------------------------------------------------
-------------------------------------------------
/app/views/_form.html.erb
-------------------------------------------------
<%= form_for(#profile) do |f| %>
<% if #profile.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#profile.errors.count, "error") %> prohibited this profile from being saved:</h2>
<ul>
<% #profile.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :prof_type, 'Profile Type' %><br />
<%= f.select :prof_type, Profile::PROFILE_TYPES, prompt: 'Select a type' %>
</div>
<div class="field">
<%= f.label :trait_ids, "Traits" %><br />
<%= f.collection_select :trait_ids, Trait.order(:name), :id, :name, {}, { multiple: true } %>
</div>
<div class="field">
<%= f.label :active %><br />
<%= f.check_box :active %>
</div>
<div class="actions">
<%= f.submit 'Update' %>
</div>
<% end %>
-------------------------------------------------
UPDATED CONTROLLER:
(traits_controller)
# GET /traits/:trait_type/trait_options
# GET /traits/:trait_type/trait_options.json
def trait_options
#traits = Trait.order(:name).where("trait_type like ?", params[:trait_type])
respond_to do |format|
format.html # trait_options.html.erb
format.json { render json: #traits }
end
end
Part 1
You should add a new action to your controller (traits_controller) that takes as input one parameter profile_type and returns all traits for that profile_type as json/xml.
Part 2
Once you have this ready, You should call this action via ajax on on_change event of your profile_type dropdown. Use that data received to construct the new traits dropdown.
chosen, select2 etc, should make this very easy to accomplish once your part 1 is ready.
Update
I have never used chosen myself. But looking at its documentation, something like this might work for you
$('#profile_type').on('change', function() {
$("#traits").chosen().change( … );
$("#traits").trigger("chosen:updated");
});
This Railscast (Episode #258) demonstrates how a chosen select is populated using json data
If it is possible to drop chosen in favor of select2, I highly recommend you do it.

Rails 4: collection_select not inserting 'class' attribute?

What am I missing here? I am working with Rails 4.0.0 and trying out the new Bootstrap 3.0.0rc1. I have a simple 'recipe box' app that has a Recipe model and a Category model that feeds a 'category' field on the Recipe. In the recipes#new view, I have the following fields defined:
<h1>Create New Recipe</h1>
<%= form_for #recipe, html: { class: 'form-horizontal' } do |f| %>
<fieldset>
<legend>Main Information</legend>
<div class="form-group">
<%= f.label :name, "Recipe name", class: "col-lg-2 control-label" %>
<div class="col-lg-6">
<%= f.text_field :name, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.label :category_id, class: "col-lg-2 control-label" %>
<div class="col-lg-6">
<%= f.collection_select :category, Category.all, :id, :name, class: "form-control", prompt: "Select a category" %>
</div>
</div>
...
The text_field helper renders a properly formatted tag, complete with class attribute. However, no matter how I construct the select or collection_select helpers, I can't seem to get Rails to give me a that contains a class attribute. The code above gives me this:
<select id="recipe_category" name="recipe[category]"><option value="">Select a category</option>
...
So the prompt comes through, but the class attrib does not, so it looks like part of html_options hash is recognized. But the Bootstrap styling isn't applied. Doesn't matter if I use braces {} around the class: "form-control" or not. Doesn't matter if I use parens around the collection_select params or not. Happens with select helper as well.
Can anyone advise? Are you seeing this too?
Try using :
<%= f.collection_select :category, Category.all, :id, :name, {prompt: "Select a category"}, {class: "form-control"} %>
According to the rails documentation, first comes options and then html options. Remember that html options need to be in braces: {prompt: "Select a category"} or {class: "form-control"}.
<%= f.collection_select :category, Category.all, :id, :name, {prompt: "Select a category"}, {class: "form-control"} %>
The checked answer doesn't work, but is checked because the correct answer buried in the comments (provided by Alter Lagos). I am trying to avoid confusion by moving the actual answer out of the comments.
Try this, works for me!
<%= collection_select(:category, :category_id, #category_for_advertising, :id, :description, {}, {:class=>"dropdown-menu"}) %>
Another version of what has been answered, incorporating W3CSS:
<%= family_form.collection_select :billing_status_id,
> BillingStatus.by_tenant(#cutid).order(:description), :id,
> :description, {}, {class: 'w3-select'} %>
<%= family_form.label
> :billing_status, class: 'w3-label' %>

Simple foreach loop in MVC

<% foreach (var car in Model.AvailableCars)
{ %>
<label><%car.Text; %></label>
<% } %>
The above code throws the error
Only assignment, call, increment, decrement, and new object expressions can be used as a statement.
I know I can do it with html helpers, but why won't the above code work?
<label><%car.Text; %></label>
should read
<label><%= car.Text; %></label>
^
or you can use
<label><%: car.Text; %></label>
^
which will automatically HTML.Encode the value for you.
Add a colon to the car.Text tag to write it to the document, such as:
<label><%: car.Text %></label>
Here's a good explanation of <%: versus <%= asp.net mvc tags: <%: %> vs. <%= %>

Hide check box from controller-MVC

How can i hide/show a check box based on a value obtained from controller.
I am using the given below code for check box
<%= Html.CheckBoxFor(m =>m.IncludeCallWithNoAgents) %>
Your view model could contain a property which would be set by the controller action and which should indicate whether this checkbox should be shown or not:
<% if (Model.ShouldShowCheckBox) { %>
<%= Html.CheckBoxFor(m => m.IncludeCallWithNoAgents) %>
<% } %>