Hi i am using the date picker jquery ui in combination with rails 3.1. The date picker looks brilliant, only the date isn't stored in the database? Only sometimes...? So that's a difficult error.
This is my .js file:
$(function() {
$("#question_deadline").datepicker({ duration: 'fast', maxDate: '+2m', minDate: 'now', showOn: "button", buttonImage: "calendar.gif", buttonImageOnly: true });
$("#question_deadline").datepicker("option", "showAnim", "drop");
$("#question_deadline").datepicker("option", "dateFormat", "DD, d MM, yy");
});
In my controller there's just plain rails script:
def create
#question = Question.new(params[:question])
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
In views file _form.html.erb i use a text_field to display the date:
<div class="field">
<%= f.label :content, "Question" %><br />
<%= f.text_field :content, :placeholder => "type your question here.." %>
<%= f.text_field :deadline %><br />
</div>
Are there people who have experience with datepiacker jquery ui and rails, the ryan bates episode, didn't solve it, i think that was written in rails 2.3?
Regards,
Thijs
First, you need to show us the view where you have the datepicker element. If it's like this:
<input type="text" name="question_deadline" id="question_deadline" />
When you submit this form, the parameters you receive in your controller (in the method "create") is called question_deadline. So in that create method you should first write:
if params[:question_deadline] != ""
params[:question][:question_deadline] = params[:question_deadline]
end
#add a else if this date field is compulsory in the database
This step is important because the create method will read stuff from params[:question][:question_deadline] not from params[:question_deadline] which is returned from the view.
Thus params[:question][:question_deadline] is empty when you do #question.save
To display the date, you also need to show us the controller "show" method that should be something like:
#question = Question.find(params[:id]) #or any sql request that returns info about a question.
Then in the view you can retrieve it simply with:
<%= #question.question_deadline%>
Maybe with more code from you controller and view I can elaborate on that.
I think, Rails/Ruby is not able to parse a date in this format:
$("#question_deadline").datepicker("option", "dateFormat", "DD, d MM, yy");
// full day name, day (w/o leading zero), full month name, 4-digit year
In your controller, you might want to add a line such as
def create/update
...
#question.deadline = DateTime.strptime(params[:question][:deadline], '%A, %d %B, %Y')
# assuming my jquery-to-ruby format-mapping is adequate ;-)
if #question.save
...
end
Beware, that this code easily breaks on malformed date strings.
If you don't want to change the format to, e.g. 'yy-mm-dd' (in Ruby-land it's '%Y-%m-%d'), you may want to populate the selected date to another HTML element using the altField option and hide the actual datepicker input field via CSS:
$("#somewhere_else").datepicker(
dateFormat: "%yy-%mm-%dd",
altField: "#question_deadline",
altFormat: "DD, d MM, yy",
...
);
<%= form_for #question do |f| %>
...
<%= text_field_tag 'somewhere_else', #question.deadline %>
<%= f.hidden_field :deadline %>
...
<% end %>
That'll work, at least for me :-)
—Dominik
The other option is to update the way ActiveSupport parses dates. This is outlined in Default Date Format in Rails (Need it to be ddmmyyyy)
Related
I have a rails app that gives users assignments and prompts them via email to come back and note that their assignment is completed or take some other action. I have three different actions (remind me later, choose a different assignment, or get help from a coach) which are represented by three radio buttons. How do I group these so that the user can only choose one of the three actions at a time?
<%= form_for(#assignment, :url => user_assignment_path(#user, #assignment)) do |a| %>
<%= a.radio_button :next_reminder_date, value: (Date.today + 2) %> <h3>Remind me again in 2 days.</h3><br>
<%= a.radio_button :coach_requested, true %> <h3>I'm stuck! Have a coach contact me.</h3><br>
<%= a.radio_button :abandoned, true %> <h3>This sucks. Give me another assignment.</h3><br>
<%= a.submit "Update assignment", class: "btn btn-primary btn-large" %>
<% end %>
I think you have two options. One would be to set the values using JavaScript. When any of the values is set, you can reset the other values. This won't work if a user doesn't have JavaScript so I'd recommend option 2.
Use something like this in your View:
radio_button_tag :next_action, :next_reminder_date
radio_button_tag :next_action, :coach_requested
radio_button_tag :next_action, :abandoned
Then in your Controller:
case params[:next_action]
when :next_reminder_date
#assignment.next_reminder_date = Date.today + 2
when :coach_requested
#assignment.coach_requested = true
when :abandoned
#assignment.abondoned = true
end
I hope that helps.
I am working the acts-as-taggable-on gem and have a question about how to filter down search results based on tags users select. Here's an abridged look at my controller:
class PhotosController < ApplicationController
def index
#photos = Photo.where(["created_at > ? AND is_approved = ?", 1.months.ago, true])
#tags = ["Animals", "Architecture", "Cars", "Flowers", "Food/Drink", "General", "Landscape", "Mountains", "Nature"]
end
def search_by_tag(tag)
#photos = Photo.where('tagged_with LIKE ?', tag)
end
end
Photos/index
<% #tags.each do |tag| %>
<%= link_to tag, {:search_by_tag => tag}, :class => "tag" %>
<% end %>
This lists out all of the tags from the hash #tags defined in index, but clicking them doesn't actually filter anything down. Here's a look at what clicking one of those links produces in the log:
Started GET "/photos?search_by_tag=Animals" for 127.0.0.1 at Sun Oct 09 17:11:09 -0400 2011
Processing by PhotosController#index as HTML
Parameters: {"search_by_tag"=>"Animals"}
SQL (0.5ms) SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence'
The result I want is for the page to display only Photos that are tagged_with whichever tag was clicked on. I can't quite figure out how to accomplish this.
(Side-question: I can't seem to find a way to list out all of the tags from the tags table that acts-as-taggable-on generated. Doing something like Photo.tagged_with or Photo.tags doesn't work. I am able to see the "tags" table the gem created, and the entries inside of it; I'm just not really clear how to handle that using this gem)
Any thoughts greatly appreciated.
UPDATE
I've updated my code and am a bit closer.
class PhotosController < ApplicationController
def search_by_tag
#photos = Photo.tagged_with(params[:tag_name])
end
photos/index
<% Photo.tag_counts_on(:tags).map(&:name).each do |tag| %>
<%= link_to tag, {:action => 'search_by_tag', :tag_name => tag}, :class => "tag" %>
<% end %>
I believe this is closer, but still working through this...
You have a number of errors in your code:
Your link_to call is actually calling the index action.
Your search_by_tag method is expecting an argument, where it should be using the params hash to access the parameters passed to it in the web request.
tagged_with is a class method added by acts_as_taggable_on, not a field in your table - therefore you can't use it in the where method like you have done.
Finally, to get all the tag names: Photo.tag_counts_on(:tags_or_whatever_you_tagged_on).map(&:name)
Take a look at the acts_as_taggable_on documentation and you'll see examples of how to use tag_counts_on and tagged_with.
As for the Rails things: http://guides.rubyonrails.org/ http://railsforzombies.org/ and/or http://railscasts.com/
I want to paginate posts by month so I added following scope in Post model
class Post
include Mongoid::Document
include Mongoid::Timestamps
scope :by_month, lambda {|end_date| Post.order_by(:created_at => :asc).where(:created_at.gte => (end_date.to_date.beginning_of_month), :created_at.lte => (end_date.to_date))}
end
In my controller I put
def show
#posts = Post.by_month(Time.now).page(params[:page]).per(20)
end
In view
<%= paginate #posts, :theme => 'month_theme' %>
<%= render #posts %>
Problems:
pagination is not working by month, I want to show all result of a month in a page, replacing params[:page] by params[:month]=2 or params[:month]=Feb
How do I view 'August 2011' instead of 1,2
Loop month and year like when you goto previous while in 'Jan 2011' it will goto 'Dec 2010'
I suppose this is not really a matter of pagination. Dealing with the params[:month] value for the query is something different from the page offset switching. You might not need a pagination library for that.
How about simply creating those links like this?
controller:
#posts = Post.by_month(Time.parse(params[:month]) || Time.now)
view:
<% Post.only(:created_at).map {|p| p.created_at.to_date.beginning_of_month}.uniq.sort.each do |m| -%>
<%= link_to_unless_current m, :month => m %>
<% end -%>
Of course you can combine this query with normal pagination if needed. But the pagination links should not be mixed with the month links in that case.
I'm writing my first custom rails validation, and would like to tag the offending class with an html "error" class if they return false - I can't quite figure out how to do it. Relevant validation code below - any help appreciated.
(If it makes a difference, I'm using jQuery)
validates_each :shop do |record, attr, value|
shopvar = record.shops.map{ |s| s.email.downcase.strip }
if shopvar.count != shopvar.uniq.count
record.errors.add(attr, 'has the same email address entered more than once')
#record.errors[attr] << "You have entered this shop in the form twice"
end
end
So in your form you'd have something like this for an input field
<%= form.text_field :title %>
Since errors is a hash you could use the "include?" method like so...
errors.include?(:title)
This tells you that there's something wrong with this field. Now all you need to do is style it.
Whack on a ternary operator asi...
<% css_class = errors.include?(:title) ? "highlight_error_class" : "no_problem_class" %>
<%= form.text_field :title, :class => css_class %>
Done.
I have a HABTM-relation between the models "Snippets" and "Tags". Currently, when i save a snippet with a few tags, every tag is saved as a new record.
Now i want to check if a tag with the same name already exists and if that´s the case, i don´t want a new record, only an entry in snippets_tags to the existing record.
How can i do this?
snippet.rb:
class Snippet < ActiveRecord::Base
accepts_nested_attributes_for :tags, :allow_destroy => true, :reject_if => lambda { |a| a.values.all?(&:blank?) }
...
end
_snippet.html.erb:
<% f.fields_for :tags do |tag_form| %>
<span class="fields">
<%= tag_form.text_field :name, :class => 'tag' %>
<%= tag_form.hidden_field :_destroy %>
</span>
<% end %>
Ok, i´m impatient… after a while i found a solution that works for me. I don´t know if this is the best way, but i want to show it though.
I had to modify the solution of Ryan Bates Railscast "Auto-Complete Association", which handles a belongs_to-association to get it working with HABTM.
In my snippet-form is a new text field named tag_names, which expects a comma-separated list of tags.
Like Ryan, i use a virtual attribute to get and set the tags. I think the rest is self-explanatory, so here´s the code.
View "_snippet.html.erb"
<div class="float tags">
<%= f.label :tag_names, "Tags" %>
<%= f.text_field :tag_names %>
</div>
Model "snippet.rb":
def tag_names
# Get all related Tags as comma-separated list
tag_list = []
tags.each do |tag|
tag_list << tag.name
end
tag_list.join(', ')
end
def tag_names=(names)
# Delete tag-relations
self.tags.delete_all
# Split comma-separated list
names = names.split(', ')
# Run through each tag
names.each do |name|
tag = Tag.find_by_name(name)
if tag
# If the tag already exists, create only join-model
self.tags << tag
else
# New tag, save it and create join-model
tag = self.tags.new(:name => name)
if tag.save
self.tags << tag
end
end
end
end
This is just the basic code, not very well tested and in need of improvement, but it seemingly works and i´m happy to have a solution!