add additional class to render partial - html

I'm looking for some help regarding partials. I have created a partial for a menu on my site, but I would like to know whether I can add an additional class to a partial. More specifically, I am looking to assign an additional class to an li menu object so that I can indicate that the user is on that particular page.
Here is my code for the partial (I'm using HAML). It's named _menu.html.haml and it is located in the 'shared' folder.
.three.columns
%ul#nav
%li
%a{:href => "../pages/about"} About
%li
%a{:href => "../pages/careers"} Careers
%li
%a{:href => "../pages/contact"} Contact Us
%li
My code for the carrers.html.haml page is as follows:
code...
= render :partial => 'shared/menu'
more code...
I would like to add a .active_page class to the careers link located in the partial. This class changes the background image behind the text to indicate that the user is on a specific page. More specifically, I'd like it to look like so:
%li.active_page
%a{:href => "../pages/careers"} Careers
Is it possible to do this using partials?

The fact that you're using a partial doesn't change how you're able to use HAML, or ERB, or anything like that. If you want to add a class, yes, then just add .active_page on to an HTML tag. If it's a valid thing to do in HAML, then you can do it anywhere in a view, even if it happens to be a partial.
A partial is just modularized/reusable views. Just like you can use code inside an instance method and inside a class method, because they're just code, so can you use the same HAML code in a partial and in a "regular" view.

There are a bunch of ways to do this. I would not use partials, I would do:
%li{:class => #active_page=="careers" ? "active_page" : ""}
%a{:href => "../pages/careers"} Careers
Assuming #active_page has been created by your controller.

Related

Editing comments on show.html.erb rather than redirecting to new edit.html.erb page with Ruby on Rails

Like the title says, I am created the blog application from the Rails guide and I want to be able to edit comments made on articles without redirecting to an edit.html.erb page. I want a div that was previously hidden to appear in the middle of the screen with the edit form on it and the text fields filled with the comment that is being edited. Here is an image of the div that is going to appear in the middle of the screen.
I know how to edit comments by going to edit.html.erb but not in the same page or if this is even possible.
I am not looking for help with the css or html, but if there is a way to do this with js or rails that would be awesome. Thanks in advance!
Edit: So the answer by Satendra gets the partial to show up, but the fields do not contain the original comment that I wanted to edit. How can I get the text-fields to be populated with the comment?
Follow these steps to make edit comment on same page.
Create a partial name _edit.html.erb put your edit.html.erb code there.
Create a div in middle of the screen where you want to render this partial.
<div id="edit_comment" >
</div>
put :remote => true to your edit button link.
# change your path accordingly
<%= link_to edit_comment_path(:comment_id => comment.id), :remote => true %>
The :remote => true is the most important part here, it allows the whole Ajax business in the first place.
In comment_controller.rb inside edit function change respond_to js
def edit
#comment = Comment.find(params[:id])
respond_to do |format|
format.js
end
end
Create edit.js.erb and put below code there.
$("#edit_comment").html("<%= j render(:partial => 'edit', :locals =>{ :comment => #comment }) %>");
# use comment variable in your partial as it is passed as local.
Its Done.

Kartik Gridview conflict with my templates menu

I have a template that i was using for my project.
Look at the picture below:
This is when i am not using the kartikGrid. the dropdown menu running as well as the template want.
look at the image below:
this is when i use kartik, the dropdown menu not running anymore.
can some body tell me why it happen.
The template using different bootsrap version with kartik.
thaks.
Hope some body help me.
Imaginaroom, that did the trick for me thank you.
My top menu wasn't responding (direct link, or drop down menu) after kartik was used. I added an id to my menu widget and it did the trick.
echo Nav::widget([
'id' => 'topMenuID',
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
Manually assign different ids to all widgets, so there won't be any conflicts.
If you don't assign ids to widgets, yii gives them one automatically, but the problem occures when loading data with ajax or pjax, then Yii cannot know which ids are already used in the page.
Every widget in Yii2 has a property 'id' that you can assign in configuration array when calling a widget.
Add this code in layout or page that has problem:
$this->registerJs( "$(document).ready(function() { $('.dropdown-toggle').dropdown(); });", View::POS_END, 'ecommerceProductJs' );

How to dynamically add text fields on Rails 4? (not nested)

I'm very new to Rails and I need to dynamically add/remove input fields on a "form_for" in Rails. I am using these inputs to alter a user's profile.
Here's the snippet I want to turn dynamic:
<%= f.label :languages, "Languages" %>
<%= f.text_field :languages, class: "shortInput", value: #parsed_json_user['user']['languages']%> <br />
I have seen many tutorials using nested attributes (I'm not even exactly sure about what those are) and such but I will not be using models. As you can see, I just want an object with a multitude of values (e.g. array) since I'll be using an API to update the "User" model.
I need something like:
Languages:
English remove
add new
Should I be using fields_for? Or somehow use JS or JQuery? Any help would be appreciated.
I searched everywhere for a similar question and haven't found any but if you actually know of or find one, pointing me in the right direction would be wonderful!
Thanks in advance
#languages = User's Languages
f.collection_select :user_languages[], #languages, :id, :name , {hide_label: true, :selected => #languages.first.id} , {:style => "width: 120px",:required => true}
Update: For single form, no nesting - one option is to hack together your own jquery. I had used a different site for my testing, but this Jquery example was the one I found easier. I removed the stuff about a counter for max fields ... it goes in the /app/assests/javascript/.js ...
$(document).ready(function() {
$(".add_field_button").click(function(e){ //on add input button click
e.preventDefault();
$('.input_fields_wrap').append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(".input_fields_wrap").on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
})
});
And the html code ...
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
If you're not having luck yet - Cocoon Gem or railscast 197/198 will do what you need with jquery which is dynamic. Ignore the parts about nesting and just take what you need from it.
Also, I'm still poking around in turbolinks which had an update recently...you might be able to find an answer there...probably not exactly what you would want...
From what I can tell is that is rely's on two paths you write in rails, that are then built upon via the jquery that acts on (add/delete) :before or :after the link_to_add_association or link_to_remove_association in order to add/hide fields from view on the dom & then the update button actually pushes the whole mess to through activeRecord into the database.

rails custom html elements form

I am new in Rails and i've searched around the web and books but I couldnt find how to make custom forms when working with rails..
what happens is that I am used to write my own HTML tags and I confortable with that. I dont like to use libs like JSF (from JAVA) that writes html components for me and I dont want that rails write it for me, except for simple tags like
text_field(:post, :title, :size => 20)
# => <input type="text" id="post_title" name="post[title]" size="20" value="#{#post.title}" />
so.. how can I do that.. for example: I would like to write by myself
<input type="text" class="myclass" data="mydata" name="how-to-get-the-attribute-name-with-rails" value="how-to-get-value-with-rails" />
how can I do that?
If you want more control over the html you are creating, you can also use a content_tag
content_tag :input, "label_name", class: "myclass", data: "mydata", name: "how-to-get-the-attribute-name-with-rails", value: "how-to-get-value-with-rails"
You can supplement any html element tag for :input. So if you want a div instead, use :div etc...
As you have written above, The name of any form field in rails is in the following format
name = 'post[name]' i.e. model_name[attribute_name]
So your params hash will contain :post => {:name => value} which allows you to use mass-assignment. But if you want to get some extra parameters from the form you can directly include them in the form and give them any name as you want. It will be available in your params hash.
You can get value easily using value = <%= #object.attribute_name. %>
I am not sure if you wanted to know this or something else. Let me know if you need more help.
You can simply write html inside a Rails form, so
<input type="text" class="myclass" data="mydata" name="how-to-get-the-attribute-name-with-rails" value="how-to-get-value-with-rails" />
is perfectly valid, but note that you should use the names and id's in correct way to automatically bind them to your back end controller.
After all, what text_field(:post, :title, :size => 20) does is it convert the parameters to pure HTML (we call them helper methods in Rails).
Read here for formhelper options (using helpers will keep your code clean).

Rails: Creating HTML in a Model

I have a Publication model with a has_many relationship to Contributors. In the model, I have a method that's meant to create an html-ready by line:
def authors
authors = []
Contributor.where(:publication_id => self.id).each do |author|
authors << "link_to "+author.name+", Contributor.find("+author.id.to_s+")"
end
authors.to_sentence
end
In my view, I have the following line:
by <%= #publication.authors %>
But instead of rendering links, it renders the raw code, such as:
by link_to B, Contributor.find(1)
I've tried patching this by adding .html_safe to the end of #publication.authors, but to no avail. Is there a better way to transfer these links from the model to the view?
You're pushing strings into your authors array. It looks like valid code, so running eval on it should work. (Actually author.name will probably evaluate as an undefined symbol, so scratch that.)
A better way would be to use a has_many :authors, :model => 'Contributor' relationship on your Publication model, and you can bring up your array of Contributor objects by simply calling
#publication.authors
You'd want to iterate over these in your view like so:
<% #publication.authors.each do |author| %>
<%= link_to author.name, author %>
<% end %>
Note also that if you're displaying multiple Publication objects in a view this way, you'll want to use Publication.includes(:authors) in your controller when you're retrieving them to avoid the "N+1" problem.
Now, three lines of code doesn't seem very expensive to repeat, but there are ways to DRY that without violating the MVC pattern and cluttering your model:
Place the code to print a publication's authors into a partial, and call the partial as needed.
Place the code into a helper, include the helper and call the method as needed.
Here's a snippet from the source for to_sentence (you can adapt it for your needs, I think):
case length
when 0
""
when 1
self[0].to_s.dup
when 2
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
else
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
end
The full source can be found here.
It looks like you are trying to use haml syntax in your line. Maybe instead of using link_to, use an html hyperlink tag itself?
That being said, why are you having a model return html?
Edit: bdares answered already with what I was trying to say