user13547057
user13547057

Reputation:

How to pass id from different table in rails?

Using Devise Gem to store user. Created One to Many association between User to Project. Created One to Many Association Between User and Site and Then One to Many Association between Project and Site. But the error is i am not able to Assign project_id to Site from User Creation form. i am able to Assign from console. here is my code-

sites_controller.rb

  def create
    @site = current_user.sites.build(site_params)

    respond_to do |format|
      if @site.save
        format.html { redirect_to @site, notice: 'Transactions was successfully Uploaded.' }
        format.json { render :show, status: :created, location: @site }
      else
        format.html { render :new }
        format.json { render json: @site.errors, status: :unprocessable_entity }
      end
    end
  end

    def site_params
      params.require(:site).permit(:name, :amount)
    end

site.rb(model)

  belongs_to :user
  belongs_to :project

User.rb

  has_many :projects
  has_many :sites

project.rb

  has_many :sites, dependent: :destroy

How can i pass project_id on site creation. Is there any other simple way to resolve such problem?

Upvotes: 1

Views: 202

Answers (2)

anurag
anurag

Reputation: 2246

Based on the comments in the question:

# project_id needs to be available to the method, 
# in order to be added to site.
#
# Either pass it through params or get it from database 
# based on your business logic.

site_params = site_params.merge({project_id: project_id})
@site = current_user.sites.build(site_params)

Should help.

Upvotes: 1

benj-p
benj-p

Reputation: 425

Try permitting the foreign key as well.

    def site_params
      params.require(:site).permit(:name, :amount, :project_id)
    end

Upvotes: 0

Related Questions