I am trying to use joins in rails to retrieve some info base on a search field but I cannot seem to find the good syntax,
I have two table savings and product and saving are saving for a product. What I want is to find a saving based on the name of the product I found that this work :
Saving.all(:joins => :product, :conditions => { :products => { :title => 'Title Name' } })
It retrieve the saving corresponding to the product named Title Name.
Now how can I change that to find the savings where product title contains params[:title] ?
Thanks,
Saving.joins(:product).where('products.title like ?', "%#{params[:title]}%")
Saving.joins{product}.where{(savings.products.title =~ my{"%#{params[:term]}%"} } with squeel
Related
My aim is to build a relationship between rooms, people and work shift. So my sequel string looks like this :
x = DB[:raum].join_table(:left, DB[:platz], :rid => :id)
.join_table(:left, DB[:patient_behandlungs_link], :platz_id => :id)
.join_table(:left, DB[:patienten], :id => :patienten_id)
.join_table(:left, DB[:behandlungsverfahren], :id => :t2__behandlungsverfahren_id)
.join_table(:left, DB[:dialysezeit], :id => :t2__dialysezeit_id)
.join_table(:left, DB[:nadeln], :id => :t2__dialysenadel_id)
.join_table(:left, DB[:dialysatorzugang], :id => :t2__dialysatorzugang_id)
.where("raumnummer = ?", raumid.to_i)
It's working like this but in the resulting table there is also a field for the shift id. In this state it does not differentiate in which workshift the person is working. if i do a foreach and push the values out I get my empty nil fields with no one inside, which I want to, and I get the people which are in room raumid from all workshifts.
If I make a .filter(:schicht_id => 1) for example, then I loose my nil values. I need them to assign new people to the empty slots, so I tried (:schicht_id => 1).or(:schicht_id => nil) and similar things but I don't get my result, I want
I think i blamed sequel for something that is not related to sequel.
In the image my select box starts showing options from the second value
This behavior made me think, something was wrong with my joins and group by instructions.... i now have to figure out why the select box shows me from values form 2-9 and not from 1-9. In the HTML Site Source code all 9 Options are given.
This is strange for me.
sorry for blaming sequel.
I'm using kartik select2 widget like this:
echo Select2::widget([
'model' => $model,
'attribute' => 'script_tags',
'data' => $model->tagList,
'options' => ['multiple' => true,'placeholder' => 'Select states ...'],
'pluginOptions' => [
'tags' => true
],
]);
$model->tagList is array in this format ['id'=>'name'] populated from database.
My question is what is the best why to save it into db table because with custom tags i have response for script_tags like this
[0=>'1', 1=>'5', 2=>'math'],
i need to save new tag in table tag[fields=id, name] and relations for all tags in table tagmap[fields=id, script_id, tag_id]
should i check if is integer save relations in tagmap, if is string save first new tag in tag table then save relation in tagmap
Your approach looks fine, except when somebody explicitly enters a number as tag value. Let's imagine in your tag table ID 1 is 'foo' and ID 5 is 'bar'. There's no way to tell if you got a 'foo,bar,math' or 'foo,5,math'. You could check if those IDs actually exist in your database and act accordingly, but that's probably overkill.
However, I suggest you take a look at some tagging solutions that already exist. I'm pretty happy with 2amigos/yii2-taggable-behavior, but there's also creocoder/yii2-taggable and probably many others.
As an added benefit, 2amigos taggable also stores tag frequencies.
Keep in mind that having an id column in tagmap, which I bet is an autoincrement PK, is bad practice, you should use (script_id, tag_id) as a composite PK.
I am working in Rails 2.3.x on a learning management system. Here's my code:
-#users.each do |user|
%tr
%td
=link_to h(user.name), :action => :show_user, :id => user.id
%td="#{h user.grade_level}"
-if QuizResult.find_by_user_id(#user_id).present?
="#{(QuizResult.average('score', :conditions => 'user_id = #{#user.id}') * 100).round}%"
-else
%em No quizzes taken
My quiz_results table has columns for user_id and score, among others. I have a record with a user_id (3907) and result (0.1), and two users I'm looking at with no records in the quiz_results table.
The display says "No quizzes taken" for all three, which leads me to believe that this line is false no matter what:
-if QuizResult.find_by_user_id(#user_id).present?
Any ideas how to fix?
Change #user_id to user.id in the if statement and #user.id to user.id. Also change the single quotations to double quotations or using string interpolation won't work.
I guess you need to change #user.id to user.id.
As the answer to second part of your question, I think you can't have a nested evaluated string (the nested #{}). You need to compute the results first, then evaluate and output it in HAML:
-averge = QuizResult.average('score', :conditions => 'user_id = #{#user.id}') * 100).round
="#{average}%"
I have a typical forum style app. There is a Topics model which has_many Posts.
What I want to do using Rails 2.3.x is query the topics table and sort by the most recent post in that topic.
#topics = Topic.paginate :page => params[:page], :per_page => 25,
:include => :posts, :order => 'HELP'
I'm sure this is a simple one but no joy with Google. Thanks.
Sorting on a joined column is probably a bad idea and will take an enormous amount of time to run in many situations. What would be better is to twiddle a special date field on the Topic model when a new Post is created:
class Post < ActiveRecord::Base
after_create :update_topic_activity_at
protected
def update_topic_activity_at
Topic.update_all({ :activity_at => Time.now }, { :id => self.topic_id})
end
end
Then you can easily sort on the activity_at column as required.
When adding this column you can always populate the initial activity_at with the highest posting time if you have existing data to migrate.
I currently have a table that is listed as follows:
projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])
where
conditions = Project.in_used_projects(:alias => "projects")
However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names. Is there anyway I can bind variables from another table in Ruby? The Project.find(all) automatically passes the SELECT * FROM Project into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?
EDIT 1
I have tried the suggested answer of using
projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
but now I am getting another error
Mysql::Error: Unknown table 'projects': SELECTprojects.* FROMprojectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')
Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?
Try this out for size:
projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
The :joins option tells Active Record to perform an SQL join onto the tags table, which will allow you to perform queries on the tags column. Also take note in this example how I've added the projects. prefix to your original name column. This is so your database doesn't get confused what name column you want; the one from the projects or the tags table.
Do you have any relationship between projects and tags? If the reason for your query is that there is, it should be reflected in the model (for ex with a HABTM), which would also enable you to easily filter based on that relationship without the need to have complex SQL queries crafted.
Turns out that it was just a simple syntax error
projects = Project.find(:all, :joins=>:tags, :conditions => [conditions + "AN rojects.name LIKE ? OR projects.description LIKE ? OR tags.name LIKE ?)", "%# ams[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%"])
is the correct syntax. The :joins needs to be followed by :tags, not by "tags"
Thanks again for everyone's help