Scott S.
Scott S.

Reputation: 759

How do I access data from a model the present model belongs to?

I have two models Issue and Split.

Issues have many Splits, a Split belongs to an Issue. Here is the code for the two models:

class Issue < ActiveRecord::Base

    belongs_to :publication
    has_many :splits
    has_many :issue_split_geographies
    belongs_to :medium

    validates :name, :start_date, :status, presence: true
end

class Split < ActiveRecord::Base
    belongs_to :issue
    has_and_belongs_to_many :geographies 
    has_and_belongs_to_many :media 
end

I know how to access split information from an issue in my Issue views by doing @issue.split.name if I want to get a split name in my issue view.

I'm having problems figuring out how to go the other way. How can I show Issue information in a Split view?

@split.issue.target gives me undefined method `issue' for nil:NilClass

split.issue.target gives me undefined local variable or method `split' for

issue.target gives me "undefined local variable or method `issue' for"

I'm trying to show the target value for the issue on the splits index page so I can determine how many more splits to add to reach my target.

It seems like I'm missing something obvious. But, I'm a bit of a noob.

Thanks

Upvotes: 2

Views: 113

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

@split.issue.target

is the right way to go as your split belongs_to issue. So, @split.issue is fine. Just make sure you define @split in your corresponding controller's action and you have issue_id in your splits table.

But, as you mention: @issue.split.name, which should not be correct as your issue has_many splits. It should be like: @issue.splits.first.name

Your error message:

@split.issue.target gives me undefined method `issue' for nil:NilClass

means that @split is nil. So, define @split in your correspnding controller's action/method. Something like this:

@split = Split.first

Then, it should work.

Upvotes: 1

Related Questions