Getting specific items from iterating rails 3 - ruby-on-rails

I am trying to find a way to pull all notes that are assigned to a course but only when necessary. I have a show page which shows all of the notes for a quiz.
course show.html.erb
<%= #course.name %>
<% #quiz.notes.each do |note| %>
<%= link_to note.title, quiz_note_path(#quiz, note) %><br/>
<% end %>
The above code works find except it pulls all of the notes and not the notes that are assigned to that course. How can I tell rails to only pull the note if note and course name are equal?
update!
In the note new.html.erb I have am using collection_select
<%= f.collection_select(:course_ids, #quiz.courses, :id, :note_name, options = {:prompt => "Choose"}) %>

It seems like you don't have relationship between course and quiz.
A course has many quizzes, a quiz has many notes. You should setup your relationship this way, so it won't pull out unnecessary notes that are not related to the current course.
The trick here is to pull all notes inside a course by using has_many :through.
class Course < ActiveRecord::Base
has_many :quizzes
has_many :notes, :through => quizzes
end
class Quiz < ActiveRecord::Base
has_many :notes
end
class Note < ActiveRecord::Base
belongs_to :quiz
end
<%= #course.name %>
<% #course.notes.each do |note| %>
<%= link_to note.title, quiz_note_path(note.quiz, note) %><br/>
<% end %>

Try something like this.
<%= #course.name %>
<% #quiz.notes.select { |n| n.title == #course.name }.each do |note| %>
<%= link_to note.title, quiz_note_path(#quiz, note) %><br/>
<% end %>
Enumerable.select evaluates the block and returns only the elements for which it was true.

Related

Displaying User Avatar (without duplicates) for each post in a Collection List with Rails 5

👋 all,
I want to display a list of collections with many posts.
So I call all collections in the controller as:
def index
#collections = Collection.order("RANDOM()")
end
Then in the View:
<% #collections.each do |collection| %>
<%= link_to collection.title, collection %>(<%= collection.posts.count %>)
<!-- Designers (Users) -->
<% collection.posts.each do |post_designer| %>
<!-- I want to display designer avatars in here, I have designer_id from the post, but how do I access Designer table to pull avatar? -->
<%= post_designer.designer_id %>
<% end %>
<!-- Images -->
<% collection.posts.each do |post| %>
<%= link_to image_tag(post.image.thumb.url.to_s, class: "fr"), collection %>
<% end %>
<% end %>
My question is that:
I want to display designer avatars in here instead of designer_id, I have designer_id from the post, but how do I access Designer table to pull avatar?
Thank you!!!! 🙏
Relations:
models/collection.rb
class Collection < ApplicationRecord
belongs_to :designer
has_many :collectivizations
has_many :posts, through: :collectivizations
end
models/collectivization.rb
class Collectivization < ApplicationRecord
belongs_to :post
belongs_to :collection
end
models/post.rb
class Post < ApplicationRecord
belongs_to :category
belongs_to :designer
has_many :collectivizations
has_many :collections, through: :collectivizations
---------------
👍 SOLUTION
It looks like I just an obvious typo error! 🤦‍♂️ The code below works, but it gives dublicates if there is more than 1 post for an user. How can I fix the duplicates?
<% collection.posts.each do |post_designer| %>
<%= link_to image_tag(post_designer.designer.avatar.url.to_s, class: "avatar-small ml1"), post_designer, class: "fl" %>
<% end %>
Try change your code like below. It will fetch first post for designer and you won't see any duplicates for designer.
<% collection.posts.select("DISTINCT ON (designer_id) *").each do |post_designer| %>
<%= link_to image_tag(post_designer.designer.avatar.url.to_s, class: "avatar-small ml1"), post_designer, class: "fl" %>
<% end %>

Rails Forms Passing Array in Params for M to M Associaton

Edit: Essentially looking to pass something like this:
{
'tabled_id' : '1',
'recipes' : [{
{ 'recipe_id' : '3',
'quantity' : '2'
}
{ 'recipe_id' : '5',
'quantity' : '1'
}
}]
}
And I think I should do params.require(:order).permit(:table_id, {recipes:, [:id,:quantity]} ) on the controller side.
I'm learning Rails building an ordering system and I'm stuck trying to build a form for Orders that passes quantity. Where Orders is a nested resource for Restaurant.
My models look like this:
class Restaurant < ActiveRecord::Base
has_many :orders
has_many :recipes, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes, dependent: :destroy
has_many :recipes, through: :order_recipes
end
class Recipe < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes
has_many :orders, through: :order_recipes
end
View:
<%= form_for([#restaurant, #order]) do |order_form| %>
<%= order_form.label :Table_Number %>
<%= order_form.number_field :table_id %>
<h3>Recipes: </h3>
<br>
<% #restaurant.recipes.each do |recipe| %>
<%= order_form.fields_for :recipe, recipe do |r| %>
<%= r.label recipe.name %>
<%= r.hidden_field :id %>
<%= r.number_field :quantity %>
<% end %>
<% end %>
<%= order_form.submit(#order.new_record? ? "Create Order" : "Edit Order", class: "btn btn-success") %>
<% end %>
This will yield a form that looks correct, but won't pass all parameters. Let's say I have 3 recipes. And I set their quantities to 2,3,4 respectively, and the table_id to 1. When I inspect the parameters, I see that only the last recipe with its quantity has been passed. params[:order] => {"table_id"=>"1", "recipe"=>{"id"=>"4", "quantity"=>"4"}} I need to be able to send all recipes with their assigned quantities. Also, I'm using the accepted answer in this question to be able to access the quantity column: Rails 4 Accessing Join Table Attributes
When you hand in fields_for :recipes multiple times, the fields_for method is not aware of you sending an array of things. Therefore it will name the parameters as if it was only one instance, so only the last instance will come through. You have to hand in the array of recipes to the fields_for, so it can name the parameters, so that rails knows it is an array of things when it gets picked up again (docs).
This is because form parameters in browsers do not support nesting by default. The actual parameters are flat key-value paramters. Rails has some naming conventions on how paramters can be named, so they will automatically be coerced to an array.
<%= form_for([#restaurant, #order]) do |order_form| %>
<%= order_form.label :Table_Number %>
<%= order_form.number_field :table_id %>
<h3>Recipes: </h3>
<br>
<%= order_form.fields_for :recipes, #restaurant.recipes do |r| %>
<%= r.label recipe.name %>
<%= r.hidden_field :id %>
<%= r.number_field :quantity %>
<% end %>
<%= order_form.submit(#order.new_record? ? "Create Order" : "Edit Order", class: "btn btn-success") %>
<% end %>

Text_field not showing up

I'm building an open-source spreadsheet application. So far, its a rails application that has 4 models: table, row, column, and item.
Here is what they look like:
Table.rb:
has_many :columns
has_many :rows
accepts_nested_attributes_for :columns
Column.rb
belongs_to :table
has_many :items
Row.rb
belongs_to :table
has_many :items
accepts_nested_attributes_for :items
Item.rb
belongs_to :row
On the page where you add a new row. You should be presented with something like this:
So the columns are already set, so now you are adding new items which when inserted should include the row_id, column_id, and value for each item.
So far my form looks like this:
<%= nested_form_for [#table, #row] do |f| %>
<% #columns.each do |column| %>
<%= column.name %> <br>
<%= f.fields_for :items do |item_form| %>
<%= item_form.text_field :value %>
<% end %>
<% end%>
<%= f.submit %>
<% end %>
I'm using the nested_form for the nested forms. But so far, I can't get a textbox for the item's value to show up. Also, is this the best way to get what I want (like the picture), or is there a cleaner way?
Thanks for all help!
You'll need to build at least 1 item for fields_for to render anything. Try doing this in your new controller action.
def new
...
#row.items.build
end

Nested model form with mutliple has_many/belongs_to associations

I have three models:
class Rate < ActiveRecord::Base
attr_accessible :user_id, :car_id, :rate
belongs_to :user
belongs_to :car
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :rates
accepts_nested_attributes_for :rates
end
class Car < ActiveRecord::Base
attr_accessible :name
has_many :rates
accepts_nested_attributes_for :rates
end
And one controller:
class UsersController < ResourceController
def new
# Assume user is loaded
#user.rates.build
end
end
I'm trying to build a nested form that will associate a list of users/cars and their associated rates.
Something like:
<% form_for #user do |f| %>
<%= #user.name %><br />
<% Car.all.each do |car| %>
<%= car.name %><br />
<%= f.fields_for :rates do |r| %>
<%= r.number_field :rate %>
<% end %>
<% end %>
<% end %>
The problem is that I would like the Rate model to store data as follows:
USER_ID CAR_ID RATE
1 1 10
1 2 20
1 3 30
2 1 40
3 2 50
I cannot figure out how to properly build the fields_for helper to build the proper params for both the user_id and the car_id.
Something like:
user[car=1][rate]
user[car=2][rate]
I've tried being more explicit with the fields_for like this:
<%= r.fields_for 'user[car][rate]' %>
But it still doesn't build out the nested parameters properly. The car parameter is not correctly identified.
Any help would be appreciated! Thanks.
EDIT:
The controller action has to be under user. The example above has been shortened for brevity but other user-related attributes are available through the form so it has to use the users controller.
ANSWER:
I figured out a way to do it. I've added my own answer that explains it.
<% form_for #user do |f| %>
<%= #user.name %><br />
<%= f.fields_for :rates do |r| %>
<% Car.all.each do |car| %>
<%= car.name %><br />
<%= r.number_field :rate %>
<% end %>
<% end %>
<% end %>
This may be solution of your problem. Just check it.
The form is going to create a new rate instead of a new user, so the method should be in RatesController instead of UsersController.
With this logic the problem seems solved. You can write field_for rate[user] and field_for rate[car]
I think I've got it figured out.
In my controller, I've modified the build method as follows:
Car.all.each { |c| #user.rates.build(car_id: c.id) } if #user.rates.count == 0
Then, in my model, I need the following:
attr_accessible :rates_attributes
Finally, the fields_for block should look like this (remember, this is in the #user form object f):
<%= f.fields_for :rates do |r| %>
<%= r.hidden_field :car_id %>
<%= r.object.car.name %><br />
<%= r.number_field :rate %>
<% end %>
This builds the params hash properly and create the rate model entries when the form is submitted.
The check on existing user rates in the controller will ensure that the existing values are used in the form and new ones are not built (which I thought build took into consideration... ?).

Insert value of select_box into table attribute

I've got two tables:
Topics
-name
and
Queries
-topic_id
A query can have a topic and so I'm trying to create a select_box in my queries_form which inserts a selected topic into my topic_id attribute of my queries table.
What I already made is a functional select_box, but I'm unable to insert the selected item into the topic_id attribute...
<% form_for #query do |f| %>
....
<%= f.select :topic_id, :value => 'queries', Topic::find(:all).collect( &:name ) %>
<% f.submit "save" %>
<% end %>
Thanks a lot for helping me
First set your relationships in your model like this :
class Topic < ActiveRecord::Base
has_many :queries
end
and
class Query < ActiveRecord::Base
belongs_to :topic
end
Then you can write in your form view this:
<% form_for #query do |f| %>
....
<%= f.select :topic_id, Topic.all.collect {|topic| [topic.name, topic.id]} %>
<% f.submit "save" %>
<% end %>

Resources