I have a question about Rails. I have a table in my database without primary key with these columns – person_id, year, salary. My problem is when I want to edit one of the salary. I can’t understand how to do it. That’s my code:
Salaries controller:
def index
@salaries = Salary.all
end
def edit
@salary = Salary.find_by_person_id_and_year(params[:person_id], params[:year])
@people = Person.all
end
index.html.erb
<% @salaries.each do |salary| %>
<b><%= salary.person.Name %></b>
<b><%= salary.Year %></b>
<b><%= salary.Amount %></b>
<%= link_to "Edit", edit_salary_path(salary.person_id, salary.year)%>
<% end %>
So, I add this to my routes.rb:
get 'salaries/index', :to => 'salaries#index',:as => 'salaries'
get 'salaries/:person_id/:year', :to => 'salaries#show', :as => 'salary'
get 'salaries/new/:person_id/:year', :to => 'salaries#edit', :as => 'new_salary'
get 'salaries/edit/:person_id/:year', :to => 'salaries#edit', :as => 'edit_salary'
put 'salaries/:person_id/:year', :to => 'salaries#update'
post 'salaries/:person_id/:year', :to => 'salaries#create'
delete 'salaries/:person_id/:year', :to => 'salaries#destroy'
but I have these error message in my _form.html.erb: “undefined method `join’ for nil:NilClass” on this line: <%= form_for(@salary) do |f| %>
def edit
@person_id = params[:person_id]
@year = params[:year]
@salary = Salary.find_by_person_id_and_year(params[:person_id], params[:year])
@people = People.all
end
def update
@people = People.all
@salary = Salary.new(params[:salary])
if @salary.save
flash[:success] = "Successfully edited salary"
redirect_to salaries_path
else
@title = "Edit salary"
render 'edit'
end
end
_form.html.erb
<%= form_for(@salary, :url => salaries_path(:person_id => @person_id, :year => @year)) do |f| %>
Rails routing will automatically be looking for the id, so you will need to customise your routes.
For example, instead of
resources :salariesin config/routes.rb try something like:With other routes as you need such as:
And the form: