4

i am new to RoR and I am a little confused on this topic. Is the scope of variables in the controller only accessible in it's corresponding view?

for instance say I generated a Post scaffold (with blog_text and title). I also generated a controller called static with a home page view/controller resource. Is there any way I can access/print all of the posts from within my home page view? would i have to do something in my static#home function? I cant jsut do Post.all correct?

1 Answer 1

3

The controllers are tied to their corresponding views. But you need to use an instance variable (a variable with '@' in the front e.g. @variable) if you want to be able to use the variable in your views. Also, it doesn't matter what model/view/controller you're in when you request data from your db. So in response to your question, yes you can just do something like

@posts = Post.all

in any controller and then access the posts in your views. This is pretty basic stuff, you should study the guide a bit more.

Sign up to request clarification or add additional context in comments.

3 Comments

i apologize i made a dumb mistake in this late hour... this is my first time trying out RoR and I kept getting a an error that it couldnt find posts my practice blog's home page. I never did rake db:migrate... i feel like an idiot lol. apologies.
Hello steve, This holds good when it is only required to show data from stored database. But I have created three models such as member, loan and receipt. And an additional model called recovery (only to read data from all three tables and process the date). After processing data the recovery model contains the loan amount to be paid by members the next month. Now how can I show this information in view? First should I store the new info to recovery db? If so how can I insert data to db from model. Simply by calling model.create?
@learner It depends on what you want. If you don't want to repeatedly process the same data then you should store the loan amount in the db. Model.create will save the object to the db assuming you've set up Model correctly. You can show the loan amount in your view by storing it in an instance variable. Again, basic stuff. I think you underestimate how much time you'll save if you put an initial investment into studying the guide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.