ruby on rails - data is not saved in joins table -
i working on website, user can have multiple projects , multpile users can contribute single project. have project model
class project < activerecord::base #associations has_and_belongs_to_many :users end
and users model
class user < activerecord::base #associations has_and_belongs_to_many :projects end
and have created joins table name - :projects_users works fine when run code on rails console. when try save thing in controller, data not being saved in joins table. code controller
please help
class projectscontroller < applicationcontroller def new @project = project.new end def create @user = user.find(session[:user_id]) @project = project.new(project_params) if @project.save @project.users << @user redirect_to @project else flash[:error] = "project has not been created due error" render 'new' end end private def project_params params.require(:project).permit(:name,:description) end end
try using nestes_attributes_for
class answer < activerecord::base belongs_to :question end class question < activerecord::base has_many :answers accepts_nested_attributes_for :answers, allow_destroy: true end
controlller
def new @question = question.new @question.answers.build end def create @question = question.new(question_params) respond_to |format| if @question.save format.html { redirect_to @question, notice: 'question created.' } format.json { render action: 'show', status: :created, location: @question } else format.html { render action: 'new' } format.json { render json: @question.errors, status: :unprocessable_entity } end end end def question_params params.require(:question).permit(:name, :description, answers_attributes:[:content, :id, :question_id]) end
you form should this
<%= form_for(@question) |f| %> <% if @question.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@question.errors.count, "error") %> prohibited question being saved:</h2> <ul> <% @question.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :description %><br> <%= f.text_field :description %> </div> <%= f.fields_for :answer |builder| %> <%= builder.label :content %> <%= builder.text_area :content %> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %>
Comments
Post a Comment