Ok, im new to ruby and rails, I cant seem to get which I would assume to be simple working. Basically my code is to remove a reference to an association (nil it).
I want to get the name member (Team.name) of the model and save it to (team_name) before removing the association for the flash message.
Here is the controller action and Models:
def remove_resource
...
#user = User.find(params[:user_id])
team_name = #user.team.name
#user.team = nil
if #user.save
flash[:notice] = "#{#user.name} was removed from "+team_name+". They are no longer on a team."
...
end
...
end
class Team < ActiveRecord::Base
has_many :user, :class_name => "User", :foreign_key => "user_id",
:order => "team_start"
...
def ==(another_team)
if self.name != another_team.name then
return false
end
if self.location != another_team.location then
return false
end
...
true
end
...
end
class User < ActiveRecord::Base
belongs_to :team, :class_name => "Team",
:foreign_key => "team_id"
...
end
The Errors I am receiving:
NoMethodError in UsersController#remove_resource
undefined method `name' for nil:NilClass
The trace:
app/models/user.rb:50:in `=='
app/controllers/teams_controller.rb:50:in `remove_resource'
Now the error only occurs when I retrieve the
#user.team.name
If I delete this and the reference to the variable team_name, all works fine.
Thanks!
You get this error because you dont have the #user.team associated anymore. There is only a nil which doesnt have the Model specific method name. So you need to validate if threre is a team associated or not before executing methods of a associated object that may not be there.
def remove_resource
...
#user = User.find(params[:user_id])
if #user.team.nil? # Check if theres a associated object
#do sth. when theres no team to remove
else
team_name = #user.team.name
#user.team = nil
if #user.save
flash[:notice] = "#{#user.name} was removed from "+team_name+". They are no longer on a team."
...
end
...
end
Related
I'm doing an update of a form. I can't add my validation in my model for x reason, so I'm adding an error in my projects_controller in the method update. When I update it should raise the error and render :edit but it doesn't. Here is my method
def update
#project = Project.find(params[:id])
#stuff to update
#add error if no legal_media checked, unless if creative upload its own conditions
unless has_media?(#project.legal_option.authorized_format)
#project.legal_option.authorized_format.errors[:base] << "error message"
end
if #project.update_attributes(project_params)
redirect_to brief_path(#project.order.brief)
else
render :edit
end
end
the method has_media? returns false dans when I type #project.legal_option.authorized_format.errors[:base]I have my error message ["error message"].
But when I type #project.legal_option.authorized_format.valid?, it returns true
Any idea how I could make my method raise this error?
Thank you!
UPDATE trying to do the validation in the model :
Since the beginning I want to check that if my column custom_document in legal_option isn't nil (therefore the user uploaded it in the update method of the projects_controller), then, check if there is at least one media in legal_media.
Here are my models :
class LegalOption < ActiveRecord::Base
belongs_to :project
has_one :authorized_format, class_name: "LegalMedia", foreign_key: "legal_option_id"
accepts_nested_attributes_for :authorized_format
has_attached_file :custom_document
validates_attachment :custom_document, content_type: { content_type: "application/pdf" }
end
class LegalMedia < ActiveRecord::Base
belongs_to :legal_option
def self.formats
{all_media: "Tous Media", internet: "Internet", paper: "Presse papier", object: "Objets", television: "TV", radio: "Radio", cinema: "Cinéma", poster_campaign: "Affiches", :press_relation => "Relations Presse", :plv => "Publicité sur lieux de vente", :event => 'Evènementiel'}
end
end
When I did the validation in the beginning with a validate :has_media? My LegalOption.LegalMedia because legal_option_id is nil in legal_media
in the unless block, put the line:
render :edit and return
like:
unless has_media?(#project.legal_option.authorized_format)
#project.legal_option.authorized_format.errors[:base] << "error message"
render :edit and return
end
You should add a validation to the model in order for the valid? to do what you are looking for it to do.
If you look at the docs here, you'll see that valid? just runs all the validations. It doesn't check for any errors that you manually add to the object.
Rails convention dictates that validations shouldn't be implemented in the controller but rather in the model. More specifically, update_attributes just runs valid? after assigning the attributes, which itself just runs validations defined on the model. Any errors already on the model are cleared out beforehand.
If you re-write this as a custom validation on the model, update_attributes should behave as you expect:
class Project < ActiveRecord::Base
validate :legal_option_has_media
private
def legal_option_has_media
unless has_media? legal_option.authorized_format
errors.add :base, "error message"
end
end
end
I am attempting to locate a parent object in a nested controller, so that I can associate the descendant resource with the parent like so:
# teams_controller.rb <snippet only>
def index
#university = Univeresity.find(params[:university_id])
#teams = #university.teams
end
When I call find(params[:university_id]) per the snippet above & in line 6 of teams_controller.rb, I receive ActiveRecord::RecordNotFound - Couldn't find University without an ID.
I'm not only interested in fixing this issue, but would also enjoy a better understanding of finding objects without having to enter a University.find(1) value, since I grant Admin the privilege of adding universities.
The Rails Guides say the following about the two kinds of parameters in a website:
3 Parameters
You will probably want to access data sent in by the user or other
parameters in your controller actions. There are two kinds of
parameters possible in a web application. The first are parameters
that are sent as part of the URL, called query string parameters. The
query string is everything after “?” in the URL. The second type of
parameter is usually referred to as POST data. This information
usually comes from an HTML form which has been filled in by the user.
It’s called POST data because it can only be sent as part of an HTTP
POST request. Rails does not make any distinction between query string
parameters and POST parameters, and both are available in the params
hash in your controller:
It continues a little further down, explaining that the params hash is an instance of HashWithIndifferentAccess, which allows usage of both symbols and strings interchangeably for the keys.
From what I read above, my understanding is that Rails recognizes both parameters (URL & POST) and stores them in the same hash (params).
Can I pass the params hash into a find method in any controller action, or just the create/update actions? I'd also be interested in finding a readable/viewable resource to understand the update_attributes method thats called in a controller's 'update' action.
Please overlook the commented out code, as I am actively searching for answers as well.
Thanks in advance.
Here are the associated files and server log.
Webrick
teams_controller.rb
class TeamsController < ApplicationController
# before_filter :get_university
# before_filter :get_team
def index
#university = University.find(params[:univeristy_id])
#teams = #university.teams
end
def new
#university = University.find(params[:university_id])
#team = #university.teams.build
end
def create
#university = University.find(params[:university_id])
#team = #university.teams.build(params[:team])
if #team.save
redirect_to [#university, #team], success: 'Team created!'
else
render :new, error: 'There was an error processing your team'
end
end
def show
#university = University.find(params[:university_id])
#team = #university.teams.find(params[:id])
end
def edit
#university = University.find(params[:university_id])
#team = #university.teams.find(params[:id])
end
def update
#university = University.find(params[:university_id])
#team = #university.teams.find(params[:id])
if #team.update_attributes(params[:team])
redirect_to([#university, #team], success: 'Team successfully updated')
else
render(:edit, error: 'There was an error updating your team')
end
end
def destroy
#university = University.find(params[:university_id])
#team = #university.teams.find(params[:id])
#team.destroy
redirect_to university_teams_path(#university)
end
private
def get_university
#university = University.find(params[:university_id]) # can't find object without id
end
def get_team
#team = #university.teams.find(params[:id])
end
end
team.rb
class Team < ActiveRecord::Base
attr_accessible :name, :sport_type, :university_id
has_many :home_events, foreign_key: :home_team_id, class_name: 'Event'
has_many :away_events, foreign_key: :away_team_id, class_name: 'Event'
has_many :medias, as: :mediable
belongs_to :university
validates_presence_of :name, :sport_type
# scope :by_university, ->(university_id) { where(team_id: team_id).order(name: name) }
# scope :find_team, -> { Team.find_by id: id }
# scope :by_sport_type, ->(sport_type) { Team.where(sport_type: sport_type) }
# scope :with_university, joins: :teams
# def self.by_university(university_id)
# University.where(id: 1)
# University.joins(:teams).where(teams: { name: name })
# end
def self.by_university
University.where(university_id: university_id).first
end
def self.university_join
University.joins(:teams)
end
def self.by_sport_type(sport_type)
where(sport_type: sport_type)
end
def self.baseball
by_sport_type('Baseball/Softball')
end
end
university.rb
class University < ActiveRecord::Base
attr_accessible :address, :city, :name, :state, :url, :zip
has_many :teams, dependent: :destroy
validates :zip, presence: true, format: { with: /\A\d{5}(-\d+)?\z/ },
length: { minimum: 5 }
validates_presence_of :name, :address, :city, :state, :url
scope :universities, -> { University.order(name: 'ASC') }
# scope :by_teams, ->(university_id) { Team.find_by_university_id(university_id) }
# scope :team_by_university, ->(team_id) { where(team_id: team_id).order(name: name)}
def sport_type
team.sport_type
end
end
views/teams/index.html.erb
Placed in gists for formatting reasons
rake routes output: (in a public gist)
enter link description here
rails console
You're not going to want to have both:
resources :universities #lose this one
resources :universities do
resources :teams
end
As for params... you have to give a param. So, when you go to http://localhost:3000/teams there are no params, by default. If you go to http://localhost:3000/teams/3 then params[:id] = 3 and this will pull up your third team.
Keep in mind the nomenclature of an index. The index action of Teams, is going to list all of the teams. All of them. There is no one University there, so what are you actually trying to find? If anything, you'd have, for your University controller:
def show
#university = University.find(params[:id])
#teams = #university.teams
end
so, the address bar will be showing http://localhost:3000/universities/23, right? params[:id] = 23, then you can find the teams associated with that university.
I have such code:
def update
#oil = Oil.find(params[:id])
#product_types = ProductType.all
if #oil.update_attributes(params[:oil])
if #oil.other_products_cross_lists.update_attributes(:cross_value => #oil.model.to_s.gsub(/\s+/, "").upcase)
redirect_to admin_oils_path
end
else
render :layout => 'admin'
end
end
but when i run it i get:
undefined method `update_attributes' for #<ActiveRecord::Relation:0x007f7fb4cdc220>
and my other_products_cross_lists isn't updated... Also i try update_attribute and get the same error.
What i do wrong?
Also when i run my destroy method
def destroy
#oil = Oil.find(params[:id])
if #oil.destroy
if #oil.other_products_cross_lists.destroy
redirect_to admin_oils_path
end
else
render :layout => 'admin'
end
end
other_products_cross_lists didn't destroy...
How can i solve this problem?
model:
class Oil < ActiveRecord::Base
has_many :other_products_cross_lists, :foreign_key => 'main_id'
class OtherProductsCrossList < ActiveRecord::Base
belongs_to :oil
other_products_cross_lists is an association on your Oil model.
You cannot use update_attributes on an Array or ActiveRecord:Relation object.
What you should do is
#oil.other_products_cross_lists.each {|list| list.update_attributes(:cross_value => #oil.model.to_s.gsub(/\s+/, "").upcase)}
for destroying
you can use
#oil.other_products_cross_lists.delete_all
or
#oil.other_products_cross_lists.destroy_all
You should check out the difference between delete_all and destroy_all for clarity.
as the error says other_products_cross_lists is a relation (I assume your model oil has_many other_products_cross_lists).
update_attribute is a method of an instance of a model, not a method of a relation.
I don't really understand, what you want to do with you update_attribute, but if user nested_attributes, then
#oil.update_attributes(params[:oil])
takes care of updating the relation.
Also, if you define your relation beween Oil and OtherProducts as dependend: :destroy Rails handles the removel of dependent records.
I've been building messaging in a rails app for users to be able to send each other messages. I've looked at a few gems such as mailboxer but ultimately decided to build my own.
I'm hoping someone can help me put these pieces together. I've been following a similar question's answer here.
I'm testing in the rails console and I keep getting the following error:
undefined method `send_message' for #
How can I fix this?
Controller
class MessagesController < ApplicationController
# create a comment and bind it to an article and a user
def create
#user = User.find(params[:id])
#sender = current_user
#message = Message.send_message(#sender, #user)
flash[:success] = "Message Sent."
flash[:failure] = "There was an error saving your comment (empty comment or comment way to long)"
end
end
Routes
resources :users, :except => [ :create, :new ] do
resources :store
resources :messages, :only => [:create, :destroy]
end
Messages Model
class Message < ActiveRecord::Base
belongs_to :user
scope :sent, where(:sent => true)
scope :received, where(:sent => false)
def send_message(from, recipients)
recipients.each do |recipient|
msg = self.clone
msg.sent = false
msg.user_id = recipient
msg.save
end
self.update_attributes :user_id => from.id, :sent => true
end
end
You are invoking the method on a class level: Message.send_message. For this to work, it would expect a declaration like this:
def self.send_message(from, recipients)
# ...
end
But, you got this instead:
def send_message(from, recipients)
# ...
end
So, either invoke the method on the instance you need it for, or refactor to make it work on a class level.
def has_photo
if user_signed_in?
#user = User.where(:id => current_user.id).first
if #user.has_photo?
if Asset.where(:attachable_id => current_user.id).count < 4
def sub_layout
"application"
end
render :template => "profiles/no_photo"
end
end
end
end
What would be the correct way to compare the Asset.count ?
Asset.where is a query, you would be much better using relationships for this.
If
Class User
has_many :assets
end
Class Asset
belongs_to :user
end
You could just use:
#user.assets.count < 4
As long as Asset has a user_id field (or make the relationship use :attachable_id) that is correctly set (the relationship can do that too if you create the Asset correctly)
By the way, if :id is unique for each user (it should be) you can rewrite
#user = User.where(:id => current_user.id).first
as
#user = User.find(current_user.id)
Hope it helps