I was wondering if there's a way to display both my last post created and also the latest three post created in the same page.
So this is how it looks now.what I want is to keep the left column like it is,but on the right column I want my last 3 posts to be displayed:
In my welcome_controller.rb I have this index method defined #post =Post.limit(1).order("created_at desc")that limits the posts to one but if I change it to 3 it applies to both left and right column and I get this really ugly thing]:
You can retrieve last 3 posts by this query
#posts = Post.last(3)
You could define your data in the action, like
#created_post = Post.limit(1).order("created_at desc")
#last_three_posts = Post.limit(3).order("created_at desc")
and change your view accordingly but the created post will always be in the last three so you could use just #last_three_posts
#last_three_posts = Post.limit(3).order("created_at desc")
#created_post = #last_three_posts.first
Related
in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.
This is what I'm using to select posts at the moment:
posts_controller.rb
favorite_post_ids = [8,2,5]
#favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.find(new_post_ids)
and then in the view I loop over them to display the posts.
However, once a post is deleted and the controller can no longer find it, I get an error that says
Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)
What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.
UPDATE :
I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.
How would you solve this problem?
Make your posts have flag favorite of type boolean. Then you'd select them like this:
#favorite_posts = Post.where(favorite: true).limit(3)
And for new posts, you can use the timestamp
#new_posts = Post.order(created_at: :desc).limit(3)
Look, no hardcoding!
I dont encourage hardcoding. But still if that is your requirement, try
favorite_post_ids = [8,2,5]
#favorite_posts = Post.where(:id => favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.where(:id => new_post_ids)
The answers to date have not worked so I have re-written my request for help. I hope it is more clear what I am struggling with
I want to move fields from an array (Array1) returned from a table(Table1) into another array (Array2), allow edit and write each record to Table2.
Desired methodology in /new_multiple in the controller:
1. #tasks = Task.find(params[:task_ids]) # returns multiple records
#:task_ids are checkbox tags
#returned from previous form
Note: This works.
2. Move #tasks each into #event and send to existing new.html.erb form for edit and/or confirmation before creation as follows(??):
#tasks.each do |task|
#event = Event.new
#event.location = task.task_location
#event.description = task.task_description
event.start_date = start_date + task.days_from_from_start_task
..... more calculated fields
***send to form for edit, show, create and return for next record (QUESTION 1 below)
end
Note: a redirect and return in *** goes to the form, but the data does not show in the form. I haven't determined if it actually returns.
Questions:
1. Is there a way call a form from the middle of an iteration in the controller and then return to the loop for other records?
2. If not, how do I (can I?)
a)move the multiple #tasks records into an #events array as above (for display in a table in a form for edit)
b)tell the system that each individual row of the array is a new record to be written on submit
Background:
I am creating an application which allows the scheduling of sets of future events. Related tasks (sets) are saved in one table and specify a sequence and a number of days from the first task in the group for that task to occur.
The user starts the process by setting the criteria - task group and the start date from which the events will begin.
The task records are then displayed with the calculated dates/time in a table on a form using a form_tag. At this point, they look like the events that are going to be created. Each line has a check-box tag for selection of tasks in the group. After the user has "ticked" their selection of events (or all), the application returns to the controller to a method called new_multiple_events
Up to this point everything works fine and I can see the selected records that have been chosen (ticked) within the events controller using debugger.
I now want to display each record individually and allow the user to edit the calculated date and time that the event will occur plus a few other fields such as the location and notes etc. and then submit the record for creation in the events table. But this is where I am just NOT getting it.
Models:
Tasks table model:
task.task_description
task.task_location
task.task_notes
task.days_from_start_task
task.task_group_name
Event table model:
event.title = task.task_group_name
event.location = task.task_location
event.description = task.task_notes
event.start_date = start_date + task.days_from_from_start_task
etc...
I have a form which works fine for entry of individual events into the calendar and I would like to move the data from the returned tasks array (plus calculated fields) into the events array as default values for this form which will then allow the user to save the data.
Thanking you in advance for any help you can give.
I don't know how you are prepopulating the event you are editing / creating in the form, but your code states you are doing that in a model. You should however create that logic in the controller before rendering the form, so do something like this:
events_controller.rb
def new
task = Task.find(params[:task_id])
#event = Event.new
#event.title = task.task_group_name
#event.location = task.task_location
#event.description = task.task_notes
#event.start_date = start_date + task.days_from_from_start_task
end
Then create your form like you normally do with the form declaration you already found yourself: form_for #event do |f|
Please consider that I used params[:task_id], suggesting you set up your routes for events nested under tasks so that your url structure looks like (for instance): /tasks/13/events/new
Goog luck
I am closing this issue because I didn't receive a relevant answer. I wanted to allow editing of selected data from one table prior to writing the data, with additional information, to another table. To get around the issue I have instead saved the selected data to the other table and then immediately read the data for edit/update. To the user it looks the same.
I know there is a simple answer to this question but I have searched for 2 days trying to find it. I have a program in rails that lists workers in the home building industry. I ask for the following informatio occupation, first name, second name,telephone number, email address. This information is displayed without any editing of my code. I would like to display this information using the order query and showing the information using the occupation column in descending order. Please tell me the code to use and where it goes.
I assume you have a method named index inside your controller. Ok, inside the index method, you can use .order method.
Make it like this:
def index
#users = User.order(occupation: :desc)
end
Reference:
http://apidock.com/rails/ActiveRecord/QueryMethods/order
I am building an app using Rails 4 and postgresql and at the top of the home page I want to show specific content from the database which changes based on the date. My database is set up as follows:
id|question |show_month|show_day
01|"question to display on January 1"|01 |01
02|"question to display on January 2"|01 |02
03|"question to display on January 3"|01 |03
and so on.
Based on the suggestion made by Frederick, my code now looks like this:
On my questions_controller:
def index
#daily = Question.find_by(show_month: Time.now.month, show_day: Time.now.day)
end
On my View:
<%= #daily.question %>
I am getting the following error when I try to load my view. It is calling the error on what I have in my view, above.
"NoMethodError in Questions#index" undefined method `question' for nil:NilClass
clearly I am not calling it on my view correctly. Any suggestions on what it should be so that it displays the "question" string from my database?
I was able to get it to display a list of all questions by having #questions = Question.all in my controller and a questions.each do loop on my view, but now I need just one.
UPDATE: The error was caused because I was storing the month/day info as a string. I made them integers and re-ran my seeds and it works perfectly now.
If you're just interested in day/month without year then the easiest may be to replace your show_date column with a show_month and show_day column and store the month/day components in those columns
Your query would then be
Content.find_by(show_month: Time.now.month, show_day: Time.now.day)
I'm building a sort-of Twitter clone, with (amongst others), models and Hashtag and Post, which have a has_many: through: relationship with each other.
Currently, visiting /hashtags/pizza will take you to a page that shows all posts with hashtag the hashtag #pizza. I want to add functionality so you can pass multiple hashtags in a URL and see the posts which contain all of those hashtags. For example, if you visited /hashtags/pizza/pasta (or hashtags/?pizza&pasta' or whatever's easiest to implement) you'd be shown a page containing all Posts which have BOTH the hashtag #pizza and the hashtag #pasta.
How would I do this? I have no idea where to begin.
For the record, my imagined code in the controller would be something like this. Feel free to poke holes in it:
1 def show
2 requested_hashtags = ??????? # an array of hashtags e.g. ["music", "guitar"]
3 hashtag1 = Hashtag.find_by_name(requested_hashtags[0]) # in this case r_h[0] = music
4 hashtag2 = Hashtag.find_by_name(requested_hashtags[1]) # and r_h[1] = guitar
5 #posts = hashtag1.posts & hashtag2.posts
6 end
Then in my view I'd just iterate over #posts. (The above example is dumbed down in that it assumes there's always exactly two hashtags requested but the principle is the same.)
So my question is, how do I complete line 2 of the code snippet above?
You can treat the url like any other string, so you could create a url like:
hashtags/?tags=pizza,pasta
And then in your controller (line 2):
requested_hashtags = params[:tags].split(",")
Another more commonly used approach in Rails is:
hashtags/?tags[]=pizza&tags[]=pasta
and then in your controller:
requested_hashtags = params[:tags]
This second way is a pretty standard Rails convention.