My model can be described as following:
One Forum has many Threads. One Thread has many Comments.
Data is not denormalized; i.e. Threads has FK only leading to Forum and Comments has FK leading only to Thread.
What will be "The Rails Way" of selecting specific Threads and then rendering Comments in a template grouped by the thread they belong to?
Read Active Record Associations here.
Define has_many and belongs_torelationships for your Forum<> Thread and Thread<>Comment
Querying using rails interface would be quite easy for you then. Refer here
Selecting commnets of specific threads(grouped by it)
Comment.where('thread_id in ?',[specific_thread_ids_to_search]).order('thread_ids')
Related
I took a look a this question and didn't found any answer that worked for me.
I have, for example a Project model, which has_many tasks. I would like to create, from an array of attributes, many tasks for some project. So, in my project model, I would have a method like this (simplified example):
def create_tasks(tasks)
tasks.map{|t| Task.create(project: self, name: t.name)}
end
The problem is, for each task, it will make a hit on my db, and for a large number of records that wouldn't be desirable. How could I do that so ActiveRecord will make only one call to my database?
Thanks in advance!
Each call for insertion into database will be done separately (in different transactions). But you could decrease a total delay wrapping all creations in a single transaction.
Task.transaction do
tasks.each{ |task| Task.create(...) }
end
In this case all your creations will be wrapped in one atomic db transaction.
Take a look at transaction documentation.
Also you could try accepts_nested_attributes_for.
Nested attributes allow you to save attributes on associated records through the parent.
Hope it helps.
I have a rails app that works almost like a blog, and I use a tagging system to categorize the posts.
I need to add to some of the posts something similar to a "related posts" feature.
So for example if post 1 is related to post 4, at the end of the show action for post one I want to render an image of post 4 and at the same time at the end of post 4 an image of post 1.
My idea is to create a "link" model that has a HABTM relations with the post model, but I'm not sure if a "post" has many "links" trough "linkings" would be better.
Both of the ideas seem to have the same result, so which approach should I prefer?
HABTM is by nature very simple, with just a table of foreign key pairs joining models.
Typically has_many through is used when you need to add additional attributes to that join relation, and/or when you need to treat the joins as their own model.
In your case, for example, you might want the links to appear in the order that they were created. For this to happen you'd need to store the create timestamp on the relationship. For this, the simple HABTM join table is not enough, so you switch to has_many through and create a Linking model to encapsulate the join.
To continue the example, you might also make Linking a first-class resource, and have a page where you can edit/add/remove them separately from either linked Post.
Personally I've always used has_many through in the majority of cases. It just feels cleaner to me (no auto-naming table magic to accept or override, and the linking is more visible), and I find that very often, join relationships do deserve to be first class citizens.
I'm working on a Ruby on Rails project where I have a "post" model and a "reply" model. As their names suggest, they share a lot of common properties such as "author_id" and "body", but have their own respective unique properties as well (e.g. a post has a title, whereas a reply does not).
My question is: what's the best practice for dealing with two similar data models? Right now I'm treating them as two distinct models types, but as I start coding, I realized there will be a lot of repetition of code.
Take a look at mixins and modules in Ruby.
I think the best option here would be for you to create a module with the shared methods for each one and include it in both of them. That way, you don't have to repeat code and both will be independent.
You can check out the link provided by sczizzo above.
Do you ever do this?
I'm writing a Rails app. I have a situation where I have a Task model (and table), the Task has attributes, people that are allowed to view it, and a hierarchy (it may be under a project, or a business).
I also have an AssignmentController that exposes some views and functionality to the individual that's assigned to the Task - The AssignmentController uses Task.find to get the task and is the same object as the Task - it's just being updated by the Assignee and only a few columns are available to the assignee. In this case, I wanted to hide some UI, change the layout to fit the business, and the hierarchy didn't matter for the assignee of the task.
What I'm thinking of doing is creating a Task model and an Assignment model that both point at the same table (the task table). I don't see why I shouldn't do this. It would allow me to thin down the Assignment model class and isolate methods that are only used by the Task. it would also make much of the code cleaner, as far as I can tell.
I don't see much about this pattern when I search on the web. Any opinions about this?
Appreciate your thoughts...
If I understood correctly you want to subclass tables :)
Nice idea, don't see why it wouldn't work...
set_table_name "tasks" will do it, or just subclass the Task model.
But in both cases you'll get into trouble with the associations, you'll have to define belongs_to :task and belongs_to :assignment for any has_many association there it you want to do it right...
Edit:
Actually forget what I said :)
http://railscasts.com/episodes/154-polymorphic-association
You should have a join table between Assignee and Tasks. Your proposal would cause your views to be littered with if statements on weather or not you have an assignee or task. If you find that you are using similar chunks of html between the two, you can simply use partials.
Also, your proposal somewhat defies database normalization. Normalization isn't just what you need today, but what you might need tomorrow. If you have no more information on an assignee than a username it might be okay to have the same table for both models (kind of). But what about later when you want to have more information on Assignees?
Is it possible to use select fields with nested object forms feature of Rails 2.3?
Example:
Suppose you have a Article model, Category model, and a ArticleCategories join model. Article has_many Categories through ArticleCategories.
On our Edit Article form, you want to have an HTML select list of all the available categories. The user can select one or more Category names to assign to the Article (multiple select is enabled).
There are lots of ways to do this, but I'm wondering if there is a simple way to accomplish this using the nested objects feature. What would the form look like in your view?
Check out the nested form example from Github:
http://github.com/alloy/complex-form-examples
It's been a while since I looked at it, so I'm not sure if it covers exactly what you wanna do, but its a nice source for ideas / patterns.
Assuming you have defined the models and their relationships so you can do this:
#art = Article.find(article_id)
#art.categories # returns list of category objects this article is assigned to.
Then I usually use http://trendwork.kmf.de/175
You need to copy the JavaScript file into public/javascripts but after that you can just create the form element with something like:
swapselect(:article,#art,:categories,Category.find(:all).map { |cat| [cat.name, cat.id] })
(I would tend to wrap that in a helper to make the call even cleaner)
One small gotcha is that for very long lists it can run a little slow in IE6 because there's quite a lot of appendChild calls in the js which is notorioulsy slow in IE6
Update: Apologies. This doesn't really answer your original question, which was specifically about the Rails 2.3 feature. The swapselect option is version independent and doesn't make use of newer Rails functionality.