Showing only things belonging to a selected user - ruby-on-rails

I have a list of things users have created, and I am having trouble showing them based on who created them.
In my view I have
<%= form_tag({}, class: "form-inline") do %>
<%= label_tag("user_names", "Users") %>
<%= text_field_tag("user_names", params[:user_names]) %>
And then in my controller I am trying to scope it with this
if params[:user_names].present?
#random = #random.where(:user_id => :user_names)
I see the dropdown, but I'm trying to get is so the dropdown shows the users names and lets me select one, so that when I submit the form, I only see entries associated with that user.
What am I missing?

You need to find the users by username and join in the other model through the user association.
if params[:user_names].present?
#random = #random.joins(:user).where("users.username IN (?)", params[:usernames])
end

Related

populate object_id fields in rails query

I have two models. One named user, and one named orders. Users have an order_id field with the order's id. I have set up orders to belong to users and users to have many orders.
Now I would like to have a view where I show some users, and each order for that user. Obviously it would be nice if I could just get one bit object that has the users and instead of the order_id, have the actual order. I know there are some languages where you can something like this:
found_user.populate(order_id)
Is there an option to do this in rails? I have seen the select function, but it doesn't seem to work, not with User.find() anyhow, which is what I am using.
Any ideas?
When you say order belongs to user, you should have user_id in orders table but not order_id in users table.
Now I would like to have a view where I show some users, and each
order for that user.
And now in the view where you want to display the users and their orders, try the below code
<% #users.each do |user| %>
<%= user.name %> #assuming you have name field in users table.
<% user.orders.each do |order| %>
<%= order.name %> #assuming you have name field in orders table.
<% end %>
<% end %>
Where #users = User.all which is defined in the respected controller action.

Rails model relationship and forms [duplicate]

I'm attempting to make an invoice application. Here are my models which are related to my question:
UPDATE: Model information has changed due to recent suggestions
Invoice
> id
> created_at
> sales_person_id
LineItem
> id
> invoice_id
> item_id
> qty_commit (inventory only)
> qty_sold
> price (because prices change)
> ...etc
Item
> barcode
> name
> price
> ...etc
Invoice has_many items, :through => :line_items. Ditto for Item. What I want to do is that when I create a new invoice, I'd like the form to be populated with all available Items. The only time I don't want all items to be populated is when I'm viewing the invoice (so only items which exist in the LineItems table should be retrieved). Currently - and obviously - a new Invoice has no items. How do I get them listed when there is nothing currently in the collection, and how do I populate the form? Also I'd like all products to be available when creation fails (along with what the user selected through the form).
UPDATE: I can create items through the controller via the following:
#invoice = Invoice.new
# Populate the invoice with all products so that they can be selected
Item.where("stock > ?", 0).each do |i|
#invoice.items.new(i.attributes)
end
This is of course my crude attempt at doing what I want. Visually it works out great, but as predicted my form id's and such are not playing well when I actually attempt to save the model.
LineItem(#37338684) expected, got Array(#2250012)
An example of the form:
# f is form_for
<% #invoice.items.group_by{|p| p.category}.each do |category, products| %>
<%= category.name %>
<%= f.fields_for :line_items do |line_item| %>
<% for p in products %>
<%= line_item.hidden_field :tax_included, :value => p.tax_included %>
<%= p.name %>
$<%= p.price %>
<% end %>
<% end %>
<% end %>
First of all, if you explicitly want to have a join model with additional attributes in it, you should use has_many :through instead of has_and_belongs_to_many. See the RoR Guide to the differences of the two.
Second, there is no single solution for what you want to reach. I see there two typical usages, depending on the mass of possible instances, one is better than the other:
Use radio buttons to select (and deselect) where a relation should be created or deleted. See the railscast #165 how to do part of that.
You could use select menus with a button to add a relation. See railscast #88. The added relation could be shown in a list, with a delete button nearby.
Use token fields (see railscast #258) to autocomplete multiple entries in one single text entry field.
In all the situations, you normally have to check at the end, if
a relation should be deleted
kept
or created
I hope some of the ideas may show you the right solution for your problem.

Populate a select box with user names

In my view I have a form with a select
<%= label_tag("employee_names", "Employees") %>
<%= select_tag("employee_names", params[:employee_names]) %>
And then I have a bunch of users, these users have a name user.name and an id user.id.
I have a method in the controller that when given the user id, narrows my list down to a specific users objects.
if params[:employee_names].present?
#time_sheets = #time_sheets.joins(:user).where("users.id IN (?)", params[:employee_names])
end
So what I am having an issue with, is I am not sure how to populate my select box with a list of users names. And then when submitted I need it to give the users id to that method. What is the best way of doing this?
I think options_from_collection_for_select should do the trick for you.
More here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select
select_tag :employees, options_from_collection_for_select(#employees, 'id', 'name')
You're looking for collection_select.
<%= collection_select(:employee, :employee_id, #time_sheets, :id, 'Employees') %>

How to read values from multiple checkbox in ruby-on-rails

How to read values from checkbox in rails.
Suppose I have brands and products.Under brands table, I have 3 brands say nike,reebok and puma. When none of the check box is selected It should display all the products say shirts,trousers,skirts. If nike brand is selected then should display onlt nike related products.Also user should have access to select more than 1 brands and we should able to display corresponding product details.
Conceptually what you are doing is a lot like creating a form that acts as a search engine (Ryan Bates does great screen casts and can help get you if you get lost http://railscasts.com/episodes/37-simple-search-form). Instead of entering text, the form uses checkboxes to create an array of brands the user wants to see.
First Create the form
<%= form_tag your_path_here_path, method: :get do %>
<%= label_tag :Nike %>
<%= check_box_tag 'brands[]', '1' #assuming 1 is the id of the Nike brand%>
<%= label_tag :Reebok %>
<%= check_box_tag 'brands[]', '2'%>
<%= label_tag :Puma %>
<%= check_box_tag 'brands[]', '3'%>
<%= submit_tag 'Get Products'%>
<%- end %>
Then in the controller processing this request search for the products that match brands in the form like this
Products.where('brand_id IN (?)', params[:brands])
To go a bit further. People use JS for these types of problems so that as the user checks different brands the products will automatically reload on the page without the user having to hit a submit button.
This could be accomplished by writing a JQuery function that listens to check events on your brands checkboxes and then
1) makes an Ajax call in the background to get all the relevant
products
2) Removes all the products you don't currently need on the page
3) Shows all the new products.
If you don't know any JQuery this project could be an interesting way to get started learning. Again, railscasts can help http://railscasts.com/episodes/136-jquery

Using collection_select for Searching In Active Record - Rails 3.2.9

I have only used collection_select once to populate a country id on an associated model User. Now I would like to do a search of User using the same collection_select statement on another view and list the Users for a selected country. My attempts have failed. I can look at the link after a country is selected and see that the id for the country is selected. But when I click my submit button the collection_select statement resets the selected value to the default selected value and ignores the value selected. For example when I select the country of France, the id is 75. When I select France and click Search by Country the id shows up like this.
http://localhost:3000/users_admin?utf8=✓&query=&user%5Bcountry_id%5D=75
Here is the form where I have the collection_select statement. I copied the statement that I am successfully using when I add/update a record on the User model with the selected country_id. What I want my logic to do is when I select a country and click Search by Country that the selected country remains selected in the drop down list and the User records with the selected country_id are displayed on the screen. The Search by Name works as expected.
<%= form_tag users_admin_path, method: 'get' do %>
<p style="padding-left: 20px;">
<%= text_field_tag :query, params[:query], placeholder: "Search for first, last or full name" %>
<span valign="center"><%= submit_tag "Search by Name", class: "btn btn-medium btn-custom", :name => nil %></span>
<%= collection_select(:user, :country_id, Country.order('name'), :id, :name, {:selected => 233}) %>
<span valign="center"><%= submit_tag "Search by Country", class: "btn btn-medium btn-custom", :name => nil %>
</p>
<% end %>
Here is the code in my controller.
def users_admin
case
when User.where("active_user = ?", '1').count > 0 # blocked users exist
#users = User.where("active_user = ?", '1').all
when params[:commit]=='Search by Country'
#users = User.where("country_id = ?", params[:country_id]).all
else
#users = User.text_search(params[:query])
end
#microposts = Micropost.all
end
I'm not sure if the issue is with how the collection_select statement is coded or another logic problem. My first thought was that I need to somehow save the selected value from the collection_select statement then use it in my where clause. But I do not know how to recode the statement to do that and also have the default selected value as 233 which is the United States when the screen is first displayed. I also thought that maybe I should have two different forms instead of one. I just do not know the direction I should go at this point.
I have searched mainly Stack Overflow for questions regarding this issue. The questions related to collection_select for the most part were relating to uses that are way past what I will probably ever use it for. Again I have only used the collection_statement once:)
Any help will be appreciated.
collection_select should be used when you are working with a model in your form (i.e. when you use form_for #user do, not form_tag
Try something like this:
<%= select_tag :country_id, options_from_collection_for_select(Country.all, :id, :title, params[:country_id]), include_blank: true %>
The params[:country_id] parameter there makes sure that whatever country_id is passed in via the GET request will be selected in your dropdown after the user submits your search form.
btw, form_for is used when there is a model involved (being created/updated). If you're creating a search form, this isn't the case and you should be using form_tag
Read this for more information: http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease
After doing more searching I decided to display params on my view just to see what was in the hash. I did not have commit in my submit_tag so I changed to check to see if params[:country_id] was present. I was able to get the country search working with the modified code:
case
when User.where("active_user = ?", '1').count > 0 # blocked users exist
#users = User.where("active_user = ?", '1').all
when params[:country_id].present?
#users = User.where("country_id = ?", params[:country_id].to_i).all
else
#users = User.text_search(params[:query])
end
The only problem I have left (minor issue) is that in order to get the name search working properly after a country search the person has to select the blank entry in the country list. Other than that this is solved. It should not take long to figure out how to wipe out the value in params[:country_id]. Either that or I may do an implicit check for params[:query].present? . Thanks for your help. Another pair of eyes did help indeed.

Resources