0

not able to access project created by current_user.

project_controller.rb

def index
  @projects = current_user.projects.all
end

  def create
    @project = current_user.projects.build(project_params)

    respond_to do |format|
      if @project.save
        #ProjectMailer.activity_status(@project).deliver

        format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

index.html.erb

      <% @projects.each do |project| %>
        <tr>
          <td><%= project.project_name %></td>
<tr>
<% end %>

user has_many project
and project has_many user.

project.rb

has_many :users, through: :project_users

user.rb

  has_many :project_users

project_user.rb

  belongs_to :user
  belongs_to :project

associated to this post- issue in has_and_belongs_to_many association in rails

rock
  • 348
  • 4
  • 18

1 Answers1

1

Check your user.rb model, I guess it should be

has_many :project_users
has_many :projects,  through: :project_users

and in your project model:

has_many :project_users
has_many :users, through: :project_users

Refer document here https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Ninh Le
  • 1,291
  • 7
  • 13
  • no still in user view i am not able to access current created project by user. – rock Aug 07 '20 at 10:29
  • Is relation setup like your post above? In the user model it has no directive how to communicate with project model, how can u get the project of the current user? if so, what is error you encounter? – Ninh Le Aug 07 '20 at 11:19
  • there is no error after creation of project i am not able to see that project in project#index. – rock Aug 07 '20 at 13:10
  • i am passing user_id to project by hidden field on form but still not able to see project on index.html.erb – rock Aug 07 '20 at 13:11
  • there is also project_user table that does not gets updated on project create. how can i update this? – rock Aug 07 '20 at 13:20
  • First, please make sure you have set up model association correctly, to verify that you can play groud in `rails console`, second, I think `break` point will help you debug your program easy, use it at the point you consider no run correctly, I cannot help with just some too common information, or you can create a demo repo help us easy to reproduce and verify your problem – Ninh Le Aug 07 '20 at 16:20