Problems with rails helper link_to concerning class - css

I'm having difficulties with rails. In fact, I wrote these lines :
<%= link_to :controller => "offers", :action => "get_offer", :offer_slug => offer.friendly_id, {:class => "media"} do %>
.
.
.
<% end %>
My problem is that everything that is inside link_to is getting the css effects of a hyperlink (no padding, gets underlined when hover), instead of custom properties.
It's like the :class property isn't being taken into account.
Just in case, here's the full part :
<<%= link_to :controller => "offers", :action => "get_offer", :offer_slug => offer.friendly_id, {:class => "media"} do %>
<li id="<%= offer.id %>" class="media" style="border: 1px solid #696969">
<div class="col-lg-3" style="margin-bottom:0px; font-size:12px; text-align:center; margin-right:10px;">
<% if offer.subcategory.nil? %>
<img class="media-object" src="<%= asset_path "other-icon.png" %>" style="margin-bottom:5px;">
<% elsif offer.subcategory.category.icon.empty? %>
<% else %>
<img src="<%= asset_path offer.subcategory.category.icon %>" style="margin-bottom:5px; width:110px;">
<% end %>
<br/>
<% if offer.subcategory.present? %>
<b><%= offer.subcategory.category.name %></b><br/> <%= offer.subcategory.name %>
<% else %>
<b>Autres</b><br/> <%= offer.subcategory_other %>
<% end %>
</div>
<div class="media-body">
<!--Titre annonce + type contrat-->
<div style="text-align:right; margin-bottom: 10px;">
<% if offer.id >= #new_limit %>
<span class="label label-warning">New</span>
<% end %>
<span class="label label-success"><%= (offer.max_price * 0.85).ceil %> euros</span>
<span class="label label-success" style="background-color: grey"><%= (offer.customer_objective) %>
succès </span>
</div>
<h4 class="media-heading">
<%= raw(offer.name) %>
</h4>
<p>
<% if offer.description %>
<%= offer.description.split[0..60].join(" ") %>
<% if offer.description.split[0..60].count >= 59 %>
<% end %>
<% end %>
</p>
<% if offer.company_context.present? %>
<p>
<%= offer.company_context.split[0..60].join(" ") %>
<% if offer.company_context.split[0..60].count >= 59 %>
<% end %>
</p>
<% end %>
</div>
<div class="offer-tags">
<% offer.offer_tags.each do |offer_tag| %>
<span class="badge"><%= offer_tag.tag.name %></span>
<% end %>
</div>
</li>
<% end %>

Try to wrap the class in curly braces:
<%= link_to :controller => "offers", :action => "get_offer", :offer_slug => offer.friendly_id, { :class => "media" } %>
The Rails link_to helper is pretty flexible and allows a few different call signatures, which can lead to confusion. You are needing this one:
link_to(body, url_options = {}, html_options = {})
Without the wrapping braces, Rails is not clear that :class is in fact an HTML option.
Docs here. I should mention I also dropped your trailing do which implied a block that didn't seem to be there (nor was it needed).
UPDATE
I did not understand that the block was intended as the link body. In that case, the right call signature would be:
link_to(options = {}, html_options = {}) do
# name
end
So, your body is fine, but in your link_to, you want to group the URL options, followed by the HTML options. Plus I think you may need parentheses around the whole call for it to work correctly:
<%= link_to({ :controller => "offers", :action => "get_offer", :offer_slug => offer.friendly_id }, { :class => "media" }) do %>

Related

My "Delete Comment" function from my Ruby on Rails Blog Website doesn't work and I don't know why

My "Delete Comment" function from my Ruby on Rails Blog Website doesn't work and I don't know why.
Here is my error:
Routing Error
No route matches [POST] "/posts/17/comments/9"
Rails.root: C:/Sites/blog
Routes
Routes match in priority from top to bottom
"comments_controller.rb" file:
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment].permit(:name, :body))
redirect_to post_path(#post)
end
def destroy
#post = Post.find(params[:post_id])
#comment = #post.comments.find(params[:id])
#comment.destroy
redirect_to post_path(#post)
end
end
"_comment.html.erb":
<div class="comment clearfix">
<div class="comment_content">
<p class="comment_name"><strong><%= comment.name %></strong></p>
<p class="comment_body"><%= comment.body %></p>
<p class="comment_time"><%= time_ago_in_words(comment.created_at) %> Ago</p>
</div>
<p>
<%= link_to 'Delete', [comment.post, comment],
method: :detele,
class: "button",
data: {confirm: 'Are you sure?'}
%>
</p>
</div>
"_form.html.erb":
<%= form_for([#post, #post.comments.build]) do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<br>
<%= f.submit %>
<% end %>
"show.html.erb":
<div id="post_content">
<h1 class="title">
<%= #post.title %>
</h1>
<p class="date">
Submitted <%= time_ago_in_words(#post.created_at) %> Ago
| <%= link_to 'Edit', edit_post_path(#post) %>
| <%= link_to 'Delete', post_path(#post),
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
<p class="body">
<%= #post.body %>
</p>
<div id="comment">
<h2><%= #post.comments.count %> Comments </h2>
<%= render #post.comments %>
<h3>Add a comment: </h3>
<%= render "comments/form" %>
</div>
</div>
"posts.rb":
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true
validates :body, presence: true
end
"routes.rb":
Rails.application.routes.draw do
resources :posts do
resources :comments
end
root "posts#index"
end
I really don't know how to fix this. Please help me. Thank you! <3

Ruby on Rails - adding CSS to text_field

I created a form in Rails and when I add a CSS class to a text_field the form will not submit.
I am still new to rails so any help would be much appreciated.
This is my form:
<% #page_title = "Contact" %>
<hr>
<div class="col-lg-12">
<h1 class="page-header">
BK Legal Courier Corp <br />Call BK # <span style="color:#47B224">613-286-8265</span>
</h1>
</div>
<hr>
<div class="container">
<h2>Contact Us</h2>
<%= form_for :fc, :url => {:action => 'create'} do |f| %>
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field (:first_name, :class => 'form-control')%>
</div>
<div class="form-group">
<%= f.label :last_name %>
<%= f.text_field (:last_name, :class => 'form-control') %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field (:email, :class => 'form-control') %>
</div>
<div class="form-group">
<%= f.label :comment %>
<%= f.text_area (:comment, :class => 'form-control') %>
</div>
<div class="form-group">
<%= f.label :referral %>
<%= f.select (:referral, [['Friends', 1], ['News', 2], ['Online', 3], ['Other', 4]], :class => 'form-control')%>
</div>
<%= submit_tag ("Submit") %>
</form>
</div>
<% end %>
</body>
</html>
The problem is that my form will only submit without the :class => "form-control" in it. I must have brackets around each of the form field variables.
This is my routes.rb file:
Rails.application.routes.draw do
root "home#index"
match ':controller(/:action(/:id))', :via => [:get, :post]
end
This is my controller:
class HomeController < ApplicationController
def home
render("home/index")
end
def new
#fc = FeedbackCustomer.new
end
def create
# Instantiate a new object using form parameters
#fc = FeedbackCustomer.new(feedbackcustomer_params)
if #fc.save
redirect_to(:action => "home")
end
end
def application
end
private
def feedbackcustomer_params
params.require(:fc).permit(:first_name, :last_name,
:email, :comment, :referral)
end
end
Any help would be much appreciated. Thanks!
If you're using Ruby 1.9+ This should work:
<%= f.text_field :last_name, class: 'form-control' %>
If you're using a version that's older than 1.9 then this should work:
<%= f.text_field :last_name, :class => 'form-control' %>
For more information on this you can use the ActionView::Helpers::FormTagHelper API Documentation
The Form Helpers Rails Guide might be helpful to you as well.
For the most recent version of Ruby you can now also do:
<%= f.text_field :last_name, class: 'form-control' %>

Rails & Bootstrap Make button inline with text field

I'm working on a front end of web app. I would like to know how to make the button and textfield in line. Another question is how to make the error message displayed just below the textfield?
Picture:
https://www.dropbox.com/s/vsdy3730flraes3/Screen%20Shot%202013-12-01%20at%204.47.20%20PM.png
Here is the code:
<div class="input-group" align="center" >
<%= form_tag(location_search_path,method: "get" ) do %>
<%= text_field_tag('location', params[:location], :size => 150, :placeholder=> "Enter city or zip code") %>
<%= button_tag(type: "submit", class: "btn btn-success ") do %>
Search
<i class="icon-search"></i>
<% end %>
<% end %>
</div>
<% [:notice, :error, :alert].each do |level| %>
<% unless flash[level].blank? %>
<div data-alert="alert" class="alert-message <%= flash_class(level) %> fade in" align="center">
<%= content_tag :p, flash[level] %>
</div>
<% end %>
<% end %>
Add the <div class="form-inline"> to your form element to get the button and field onto the same line, and I guess you could us a <p> to make the message appear below it, though I would probably set up the input group in a row with columns to center it rather than the align tag you are using, and then put the messages into a new <row> below it in the same column.
<div class="input-group" align="center" >
<div class="form-inline">
<%= form_tag(location_search_path,method: "get" ) do %>
<%= text_field_tag('location', params[:location], :size => 150, :placeholder=> "Enter city or zip code") %>
<%= button_tag(type: "submit", class: "btn btn-success ") do %>
Search
<i class="icon-search"></i>
<% end %>
<% end %>
</div>
</div>
<p>
<% [:notice, :error, :alert].each do |level| %>
<% unless flash[level].blank? %>
<div data-alert="alert" class="alert-message <%= flash_class(level) %> fade in" align="center">
<%= content_tag :p, flash[level] %>
</div>
<% end %>
<% end %>
bootstrap 3 has input groups... which are nice. http://getbootstrap.com/components/#input-groups
Try this in your code...
<%= form_tag location_search_path, method: 'get' do %>
<%= text_field_tag :location, params[:location], size: 150, placeholder: "Enter city or zip code" %>
<span class='input-group-btn'>
<%= submit_tag 'Search', class: 'btn btn-success' %>
</span>
<% end %>

How can I remove new blank line that pops up after I execute JQuery Ajax in Rails3?

In index.html.erb, I made the button that switches from Follow to Un-follow, Follow to Un-follow back and forth when it's pressed.
It's working perfect but when I press the button, it makes another new line at right below of the button that's shown first when the page is loaded.
Why does it? and How can I remove or fix this new line??
Here are images!
image 1. When the page is loaded
image 2. When the button is pressed first time after loaded
image 3. When the button is pressed second time after loaded
My codes are
follows_controller.rb
class FollowsController < ApplicationController
def create
#user = User.find(params[:user_id])
current_user.follow(#user)
respond_to do |format|
format.js {render :action=>"create.js"}
end
end
def destroy
#user = User.find(params[:user_id])
current_user.stop_following(#user)
respond_to do |format|
format.js {render :action=>"destroy.js"}
end
end
end
views/users/_follow_user.html.erb
<% unless user == current_user %>
<% if current_user.following?(user) %>
<%= button_to("Un-Follow", user_follow_path(user.to_param, current_user.get_follow(user).id),
:method => :delete,
:remote => true,
:class => 'btn') %>
<% else %>
<%= button_to("Follow", user_follows_path(user.to_param),
:remote => true,
:class => 'btn btn-primary') %>
<% end %>
<% end %>
views/follows/create.js.erb
$('.follow_user[data-user-id="<%=#user.id%>"]').html('<%= escape_javascript(render :partial => "follow_user", :locals => {:user => #user}) %>');
#jQuery
views/follows/destroy.js.erb
$('.follow_user[data-user-id="<%=#user.id%>"]').html('<%= escape_javascript(render :partial => "follow_user", :locals => {:user => #user}) %>');
#jQuery
views/users/index.html.erb
<%- model_class = User.new.class -%>
<div class="page-header">
<h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
</div>
<% #from %>
<h3>tag cloud</h3>
<% tag_cloud(#tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
<%= link_to tag.name, {:action=>'index', :tag=>tag.name}, :class => css_class%>
<% end %>
<%= paginate #users %>
<table class="table table-condensed">
<thead></thead>
<tbody>
<% #users.each do |user| %>
<div class="memberListBox">
<div class="memberList">
<p class="name"><span><%= user.user_profile.nickname %></span>(<%= user.user_profile.age %>)</p>
<p class="size"><%= user.username %></p>
<p class="img">
<% if user.user_profile.user_avatar? %>
<%= image_tag(user.user_profile.user_avatar.url(:thumb),:height => 100, :width => 100, :class => 'img-polaroid' ) %>
<% else %>
<%= image_tag('nophoto.gif',:height => 100, :width => 100, :class => 'img-polaroid' ) %>
<% end %>
</p>
<div class="introduction">
<%= user.user_profile.introduction %>
</div>
<% if user_signed_in? && current_user!=user %>
<div class="follow_user" data-user-id="<%= user.id %>">
<%= render :partial => "follow_user", :locals => {:user => user} %>
</div>
<% end %>
<%= link_to sanitize('<i class="icon-pencil icon-white"></i> ') + 'Message', new_messages_path(user.username), :class => 'btn btn-primary' %>
<%= link_to sanitize('<i class="icon-user icon-white"></i> ') + 'Profile', show_user_path(:username => user.username, :breadcrumb => #from), :class => 'btn btn-info' %>
</div>
</div>
<% end %>
</tbody>
</table>
html when the page is loaded(image 1)
<div class="follow_user" data-user-id="3">
<form action="/users/3/follows/133" class="button_to" data-remote="true" method="post"><div><input name="_method" type="hidden" value="delete" /><input class="btn" type="submit" value="Un-Follow" /><input name="authenticity_token" type="hidden" value="eVjePZ0ajS3NfXJLDBkELnpNwyt8k1f59FiT8iv/Xb8=" /></div></form>
</div>
html when the button is pressed(image 3)
<div class="follow_user" data-user-id="3">
<form action="/users/3/follows/133" class="button_to" data-remote="true" method="post"><div><input name="_method" type="hidden" value="delete" /><input class="btn" type="submit" value="Un-Follow" /><input name="authenticity_token" type="hidden" value="S92bRkGcbMz/puQvia4m7IOtrTsO2iCThiaHlBaXmJU=" /></div></form>
</div>

ASP.NET MVC 2 - ViewModel Prefix

I want to use RenderPartial twice in my view with different models associated. The problem is that some properties are present in both models (nickname, password). They have no prefix, so even the id's or names are equal in the output. Now, if I have model errors for nickname or password, both fields get highlighted.
Main View:
<div>
<% Html.RenderPartial("Register", Model.RegisterModel); %>
</div>
<div>
<% Html.RenderPartial("Login", Model.LoginModel); %>
</div>
Login PartialView:
<% using (Html.BeginForm("Login", "Member")) { %>
<fieldset>
<legend>Login</legend>
<p>
<%= Html.LabelFor(x => x.Nickname) %>
<%= Html.TextBoxFor(x => x.Nickname) %>
</p>
<p>
<%= Html.LabelFor(x => x.Password) %>
<%= Html.PasswordFor(x => x.Password) %>
</p>
<input type="submit" value="Login" />
</fieldset>
<% } %>
Register PartialView:
<% using (Html.BeginForm("Register", "Member")) { %>
<fieldset>
<legend>Register</legend>
<p>
<%= Html.LabelFor(x => x.Nickname) %>
<%= Html.TextBoxFor(x => x.Nickname) %>
</p>
<p>
<%= Html.LabelFor(x => x.Email) %>
<%= Html.TextBoxFor(x => x.Email) %>
</p>
<p>
<%= Html.LabelFor(x => x.Password) %>
<%= Html.PasswordFor(x => x.Password) %>
</p>
<p>
<%= Html.LabelFor(x => x.PasswordRepeat) %>
<%= Html.PasswordFor(x => x.PasswordRepeat) %>
</p>
<input type="submit" value="Register" />
</fieldset>
<% } %>
How can I change this?
If you can't do an EditorTemplate for some reason, you can do this in your View:
var dataDict = new ViewDataDictionary();
dataDict.TemplateInfo.HtmlFieldPrefix = "myPrefixHere";
Html.RenderPartial("myPartialViewName", myPartialViewModel, dataDict);
Lo and behold, all inputs in your PartialView will be prefixed.
Kudos to R0MANARMY for pointing this out.
Instead of using Html.RenderPartial you could use editor templates which will handle prefixes.
So in your main view:
<div>
<%-- See below what does the second argument mean --%>
<%= Html.EditorFor(x => x.RegisterModel, "RegisterModel") %>
</div>
<div>
<%= Html.EditorFor(x => x.LoginModel, "LoginModel") %>
</div>
And then create a folder Views/Shared/EditorTemplates/RegisterModel.ascx (The name of this file is used in the EditorFor helper method). Also notice that this partial should be strongly typed to the type of the RegisterModel property:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Ns.Models.RegisterModel>" %>
<% using (Html.BeginForm("Register", "Member")) { %>
<fieldset>
<legend>Register</legend>
<p>
<%= Html.LabelFor(x => x.Nickname) %>
<%= Html.TextBoxFor(x => x.Nickname) %>
</p>
<p>
<%= Html.LabelFor(x => x.Email) %>
<%= Html.TextBoxFor(x => x.Email) %>
</p>
<p>
<%= Html.LabelFor(x => x.Password) %>
<%= Html.PasswordFor(x => x.Password) %>
</p>
<p>
<%= Html.LabelFor(x => x.PasswordRepeat) %>
<%= Html.PasswordFor(x => x.PasswordRepeat) %>
</p>
<input type="submit" value="Register" />
</fieldset>
<% } %>
You could define a different partial for the login model in Views/Shared/EditorTemplates/LoginModel.ascx
Looks like there's an overload for TextBoxFor that allows you to specify extra HTML attributes. It isn't an ideal solution, but it should let you change the id (and possibly name?) of the rendered textboxes. Of course changing the name would probably screw things up when you try to post the form.
First of all, you could use Html.TextBox("input form name", ...) and set the name to whatever you wish. There's a bigger issue how would you provide a prefix on Html.RenderPartial() level? You are already providing a model instance. So without changing their view models, there's just one more possibility: to write your own overloads for RenderPartial() that would take the prefix and pass it on to others.
Check this one out. Someone's written a whole bunch of overloads that support setting prefixes. TextBoxFor rendering to HTML with prefix on the ID attribute
If any is missing you can see the pattern how to extend these with additional ones you may need.

Resources