There is a Plan model, it contains information about which person, on which project, what week and how much% it works. You can go and see the data on a specific project, for example - /plans?project_id=17 , on the same page you can add a new entry (using JS). Record is added without problems, but how, when added, again go to the same page, and not to /plans ? How to pass the id parameter of the current project?

Rails 4

  • In the sense you add using js, but not ajax? What's the point of this ? - zb '
  • @eicto, yes AJAX is there, AJAX. In Rails, it is one option that is included for the form and for the link. Only functions for successful execution / errors register, that's all. - Risto

1 answer 1

If you do not have a route, and you simply pass the id through get, like in php, then the approach is incorrect. You must add a route to /config/routes.rb

 get "/plans/:project_id", to: 'plans#index', as: 'plans_project' 

The as parameter specifies the name of your route. By this name you can always call it.

In your PlansController, in the create method there should be an entry, like:

 def create @plan = @project.plans.new(plan_params) respond_to do |format| if @plan.save format.html { redirect_to plans_project_path(@project), notice: 'Plan was successfully created.' } format.json { render action: 'show', status: :created, location: plans_project_url(@project) } else format.html { render action: 'new' } format.json { render json: @plan.errors, status: :unprocessable_entity } end end end 

And in the new method:

 @project = Project.find(params[:project_id]) @plan = @project.plans.new 

Change redirect_to in format.htm and the location parameter render in format.json to plans_project_path and plans_project_url . As a parameter, pass them the object of the parent project, as shown in the example above.

And your index is incorrect:

 @project_id = params[:project_id] @plan = Plan.where("project_id == ?", @project_id) 

It should be replaced by:

 @project = Project.find(params[:project_id]) # Получаем объект проекта по id. @plans = @project.plans # Получаем все планы связанные с данным проектом. 

To make it work, make sure that the connections are spelled out in the models. In plan.rb:

 belongs_to :project 

And in project.rb:

 has_many :plans 
  • Sorry, first suggested how to do exactly the opposite) Record was taken from my JournalsController, and rewritten under your model name. - Risto
  • Risco, thanks for the info. There is a question: Why do I need to go to the show page, because I am sampling by project_id, and not by plans_id? I do not need to go to a specific record of the Plans model. Code in PlansController index def @project_id = params [: project_id] @plan = Plan.where ("project_id ==?", @Project_id) respond_to do | format | format.html # index.html.erb end end Perhaps this is the wrong approach? - lirikk12
  • @ lirikk12, yes, wrong. Updated his answer, enlighten) - Risto