get attributes from html to controller rails - ruby-on-rails

i have this .html
<% #resources.each do |resource| %>
<tr>
<!-- -1 es para mostrar todos los recursos que faltan % -->
<% if (resource.curso_id = params[:id] or params[:id] ="-1") and resource.cantidad>0 %>
<td><%= resource.title %></td>
<td><%= #curso.nombre %></td>
<td><%= #user.name %></td>
<!-- %= image_tag(resource.imagen_url, :width => 190, :height => 190) if resource.imagen.present? % -->
<td><%= resource.cantidad %></td>
<td><%= link_to 'Show ', resource %></td>
and this controller:
def index
if params[:id] != "-1"
#resources = Resource.where(:curso_id => params[:id])
#curso = Curso.find(params[:id])
#user = User.find(#curso.user_id)
else
#resources = Resource.all
# HERE IS THE ERROR. I WANT TO GET THE COURSE BUT I WANT THE FIELD CURSO_ID THAT IS IN RESOURCE TABLE
#cursos = Cursos.find(#resource.curso_id)
#user = User.find(#curso.user_id)
end
end
the part that is above the if works ok. but the part below doesnt work. i want to get an attribute from resource in html and use in my controller. how could it be possible? thank you!

It seems like your model associations are not set up.
class Resource < ActiveRecord::Base
belongs_to :curso
end
class Curso < ActiveRecord::Base
has_many :resources
belongs_to :user
end
class User < ActiveRecord::Base
has_many :cursos
end
After that, you can simply access them in view template:
<% #resources.each do |resource| %>
<% resource.curso %>
<% resource.curso.user %>
<% end %>
Lastly, I'd like to add that using localized names for your model attributes is a real bad practice.

#resource is not defined. You have defined #resources = Resource.all(notice the s).
Plus Resource.all returns an array or objects of type Resource. Please explain what you're trying to achieve.

Related

Access nested model attributes

I have following setup:
class EmpsController < ApplicationController
def new
#emp = Emp.new
#unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }
end
def create
#emp = Emp.new(emp_params)
#emp.save!
redirect_to :action => :list
end
def destroy
#emp = Emp.find([:id])
#emp.destroy
redirect_to :action => :list
end
def list
#emps = Emp.all
end
def emp_params
params.require(:emp).permit(:name, :unit_id)
end
end
Model:
class Emp < ApplicationRecord
has_one :units
accepts_nested_attributes_for :units
end
Form:
<p> List of Employees: </p>
<table>
<% #emps.each do |u| %>
<tr>
<td><%= u.id %></td> <td><%= u.name %></td> <td><%= u.unit_id %></td> <td><%= link_to "Delete", u, :method => :delete %></td>
</tr>
<% end %>
</table>
All I want to do is to print (in table above) unit attribute called :name related with Emp printed Emp object.
Found various related solution but they do not apply to my case.
First, don't use :units as the association name, it "has one unit" no "units", Rails convention over configuration expects the association to be singular.
Then you should be able to do some_emp.unit.name.
Or you can use method delegation:
class Emp < ApplicationRecord
has_one :unit
delegate :name, to: :unit
end
And now you can do some_emp.name.

Rails - error while showing field from class

i want to bring all the resources and then show the 'nombre' field that is from 'curso'. One curso has many resources.( I have all the has_many and belongs_to well configured.)
For that i do the following:
resources_controller:
def index
#resources = Resource.all
end
index.html:
<% #resources.each do |resource| %>
<tr>
<td><%= resource.title %></td>
**<td><%= resource.curso.nombre %></td>**
<td><%= resource.cantidad %></td>
<td><%= link_to 'Show ', resource %></td>
<% else %>
<% end %>
but when i test it, it gives me the following error: "undefined method `nombre' for nil:NilClass"
do you know what can it be?
thanks!
It means that this particular resource is not associated with any of your curso.
If you want to mandate that each resource should be associated with any of your curso while it's creation, you should have this in your Resource model:
class Resource < ActiveRecord::Base
belongs_to :curso
# Validate the presence of curso in every resource.
validates :curso, presence: true
end
class Curso < ActiveRecord::Base
# When any curso is destroyed, all it's associated resources should be gone.
has_many :resources, dependent: :destroy
end
Only in above case, you can ensure that resource always have a curso during it's creation.
Additionally, you can have DB level not null constraint on curso_id field of resources table.
Seems like some resources dont have acurso`.
Just check if the curso exists before calling nombre on it:
<%= resource.curso.nombre if resource.curso %>
or
<%= resource.curso && resource.curso.nombre %>
or
<%= resource.curso.try(:nombre) %>

Edit multiple saved records

I'm trying to develop a simple exercise log app, and I'm stuck (again). A user selects a category, and a specific workout, and I return a list of exercises belonging to that workout.
An effort is a user specific instance of an exercise.
class Exercise < ActiveRecord::Base
has_many :efforts
end
class Effort < ActiveRecord::Base
belongs_to :exercise
end
I'm retrieving the list of exercises in the efforts controller
class EffortsController < ApplicationController
def log_workout
#exercises = Exercise.where("category_id = ? AND workout_id = ?", params[:exercise][:category_id], params[:exercise][:workout_id])
#effort = Effort.new
end
end
The user logs their workout by using the following form
<%= form_tag save_workout_path, method: :put do %>
<table>
<tr>
<th>Exercise</th>
<th>Sets</th>
<th>Reps</th>
</tr>
<% #exercises.each do |exercise| %>
<%= fields_for "efforts[]", #effort do |f| %>
<tr>
<td><%= exercise.name %></td>
<td><%= f.number_field :sets %></td>
<td><%= f.number_field :reps %></td>
<%= f.hidden_field :exercise_id, :value => exercise.id %>
</tr>
<% end %>
<% end %>
</table>
<%= submit_tag "Log it" %>
<% end %>
class EffortsController < ApplicationController
def create
params[:efforts].each do |values|
if current_user.efforts.create(values)
flash[:notice] = 'Efforts were successfully saved.'
else
render action: 'new'
end
end
end
end
How right this is, I'm not sure, but it works. My problem now is trying to retrieve saved 'efforts' and allowing them to be modified through the same form. (Letting the user edit their workout log). Would appreciate any guidance/help

Why do I get this NoMethodError

I'm making a twitter-copy and right now I'm trying to show all the posts from the users an other user is following. I'm new at ruby and rails, so i might be doing this a really weird way..
These are the files I have:
session#home.html.erb
<h2 class='User_Header'> Home <h2>
<%= link_to "New Post", controller: "posts", action: "new" %>
<%= link_to "Log Out", :controller => "sessions", :action => "logout" %>
<%= show_tweets("following") %>
sessions_helper
module SessionsHelper
def show_tweets(opt)
if opt == "following"
#sub = Subscription.where("userID = ?", #current_user.id)
#post = Post.where("user_id = ?", #sub.followingID)
render partial: 'shared/follower_tweets'
end
end
def show_tweet(s)
#post = Post.where("user_id = ?", s.id)
render partial: 'shared/tweet'
end
def tweet_username(p)
#username = User.where("id = ?", p.user_id)
Rails.logger.debug #username.inspect
render partial: 'shared/user'
end
end
_follower_tweets.html.erb
<h2>Tweets</h2>
<table>
<tr>
<th>Username</th>
<th>Tweet</th>
</tr>
<% div_for(#post, class: 'post') do %>
<td><%= tweet_username(#post) %></td>
<td><%= #post.content %></td>
<% end %>
</table>
_user.html.erb
<%= #username %>
session.rb
class Session < ActiveRecord::Base
attr_accessible :content, :user_id, :followingID, :userID
end
Error
app/views/sessions/home.html.erb where line #9 raised:
undefined method `followingID' for #<ActiveRecord::Relation:0x007fd74b66f8a8>
What is happening is that you have followingID on your Session model instead of Subscription model. Should be something like the following:
class Subscription < ActiveRecord::Base
attr_accessible :followingID
end
However, the problem is bigger than that. You must read about Active Record Associations, then you would be able to do something like
#subs = #current_user.subscriptions
#posts = #current_user.posts
check if your model's association is correct. the messages indicates that there's an error about this.

pass variables between two controllers

I have two controllers: tasks, tasksperson.
I have views/tasks/index.html.erb:
<table>
<% #tasks.group_by(&:name).each do |name, tasks| %>
<tr>
<td><%= name %></td>
<td><%= tasks.size %></td>
<td><%= tasks.select{ |task| task.done != true }.size %></td>
</tr>
<% end %>
</table>
I want to create a link in views/tasks/index.html to views/tasksperson/index.html.erb.I want also to send the name into 'index' in Tasksperson_controller.. I tried to do this by getting params[:name] but I think it's wrong
maybe, I need to do something like:
<td><%= link_to 'Show Tasks', tasksperson_path(name) %></td>
this is my tasksperson_controller:
class TaskspersonController < ApplicationController
def index
#tasks = Task.where(:name => params[:name]) respond_to do |format|
format.html # index.html.erb
format.json { render json: #tasks }
end
end
end
and views/tasksperson/index.html.erb:
<table>
<tr>
<th>Name</th>
<th>num of tasks</th>
<th>num tasks left</th>
<th>test</th>
</tr>
<% #tasks.each do |f| %>
<tr>
<td><%= f.name %></td>
<td><%= f.task %></td>
<td><%= f.done %></td>
</tr>
<% end %>
</table>
You need to add :name as a parameter to the rule that defines the route to TaskspersonController#index in routes.rb
so it would be something like this:
match 'tasksperson/index/:name' => 'tasksperson#index', as: :tasksperson_path
Based on your comment "...so Task have many taskpersons" I think you want a data model similar to below
class Task < ActiveRecord::Base
has_many :assigned_tasks
has_many :people, :through => :assigned_tasks
end
# maybe this is just the User class?
class Person < ActiveRecord::Base
has_many :assigned_tasks
has_many :tasks, :through => :assigned_tasks
end
# was TaskPerson
class AssignedTask < ActiveRecord::Base
belongs_to :task
belongs_to :person
end
See http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association for information about "The has_many :through Association"
task = Task.create(:title => "Go up the hill")
jack = Person.find(00000)
jill = Person.find(00000)
task.people << jack
task.people << jill
task.assigned_tasks.each do |join|
puts join.created_at
puts join.person.name
# 0 - jack
# 1 - jill
end
task.people.each do |person|
puts person.name
end
I am not exactly sure what you are trying to display in your views, it looks like you are grouping by a task name attribute in task/index, is that the Persons name?

Resources