Reputation: 634
I have a has_many :through relationship, and the fallowing scenario:
A user is able to create an project
and add many words
to that project. The 'words' will be stored just once in the database, and if they already exist in the join table an association will be created.
What I have so far:
A project controller
which is adding the project into the table and redirects to a show page, where is another simple_form_for in where all the words will go.
def show
@word = word.new
end
Project show View
<%= simple_form_for @word do |f|%>
<%=f.input :name%>
<%=f.button :submit%>
<%end%>
In the word controller
create action
I would like to get the project id and populate the join table
and the words
table.
@project = Project.find(params[:id])
So how can I get the project_id
and populate the join table and use find_or_create_by
populate the words
table.
(I know that the project_id
can be found in the URL, also I can print it by using @project.id
) in the view
Thank you
Upvotes: 1
Views: 127
Reputation: 370
If I am getting the question right, you want to create a has_and_belongs_to_many relationship between project and word. so in your Project.rb add
has_and_belongs_to_many :words
and in your Word.rb add
has_and_belongs_to_many :projects
Now for this relationship create a new table projects_words with two fields 'project_id' and 'word_id'
In project controller inside show action
@words = Word.new
In show page of project add this:-
<%= form_for @word,:url => words_path(:project_id => @project.id) do |f|%>
<%=f.label :name%>
<%=f.text_field :name%>
<%=f.button :submit%>
<%end%>
Now in the word controller create action do like this:-
@word = Word.find_or_create_by_name(params[:word][:name])
@word.projects = Project.where(:id => params[:project_id])
@word.save
Upvotes: 2
Reputation: 3011
I think you can pass Project ID in the URL like this,
Projects Controller:
def show
@project = Project.find(params[:id])
end
projects/show.html.erb
<%= simple_form_for @word, :url => words_path(:project_id=> @project.id), :method => :post do |f| %>
<%=f.input :name%>
<%=f.button :submit%>
<%end%>
Sorry if this didn't work, I haven't tested this.
Upvotes: 0